Nunjucks: Unable to include raw contents of file

Created on 6 Jul 2016  路  8Comments  路  Source: mozilla/nunjucks

Basically I am wondering if there is any way to include another file's raw content, e.g. without parsing it's content.

My usecase is this:
I'm working on a static site that's generated by nunjucks. For runtime templates i use Handlebars, so I want to separate my nunjucks and handlebars files.

I would expect something like this to work:

<script type="text/x-handlebars-template" data-partial-template-name="Subscriber">
  {% include "./subscriber.hbs" raw %}
</script>

... But that obviously doesn't work. My only option right now is to wrap the inside of the file with {% raw %}...{% endraw %} to escape the handlebars syntax.

Any suggestions on how to solve this?

enhancement

Most helpful comment

Well, in fact even addGlobal will do

Something like

fs = require('fs')

env.addGlobal('includeFile', (src) => fs.readFileSync(src)

And then

```jinja
{{ includeFile('myfile.css') }}
````

All 8 comments

There's nothing built-in for that. You could build your own template tag, though that's unfortunately not all that well documented. Another option is to configure your nunjucks env with alternate syntax (see the docs) so it doesn't conflict with Handlebars syntax.

Ok. It seems to me to be a pretty common use case though, so maybe you can reopen and tag it feature request if you agree?

What about macro with caller() which will encapsulate {% raw %}...{% endraw %} wrappers?

This would also be useful for inlining minified css.

<style>{% includeraw "inline.min.css" %}</style>

should result in:

<style>{% raw %}(content){% endraw %}</style>.

The reason being that there is valid css that is read by nunjucks as a comment. Namely, any id selector inside an @-rule (@media screen{#myid { ... }).

I think as for now there is no other option except to write your own extension

Well, in fact even addGlobal will do

Something like

fs = require('fs')

env.addGlobal('includeFile', (src) => fs.readFileSync(src)

And then

```jinja
{{ includeFile('myfile.css') }}
````

fs.readFileSync does the job, assuming you run nunjucks with autoescape: false.

Sorry for reviving an old thread, but I need the same thing in my project, i.e. prevent Nunjucks from evaluating variables, just read the template "as is". Are there any news on this?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

atian25 picture atian25  路  5Comments

kamlekar picture kamlekar  路  5Comments

RomainLanz picture RomainLanz  路  4Comments

wslx520 picture wslx520  路  4Comments

kud picture kud  路  3Comments