Access to a the templating context object in filter functions
See original GitHub issueIt would be quite useful to have access to the render
context object inside filter functions; especially for localisation this could be very useful (at the very least for webmaker).
A use case:
we have a batch of key/strings that include templating vars:
"welcome": "welcome to the site, {{username}}"
"about": "<a href='{{lang}}/about'>click here</a>"
...
these are added (server-side) to our own template files, such as an index.html:
<html>
...
<p>{{ getText("welcome") }}</p>
...
<footer>{{ getText("about") }}</footer>
...
</html>
We render these the usual way, using a res.render("index.html", {...})
, but this only gets us half-way there - the rendered data will look like:
<html>
...
<p>welcome to the site, {{username}}</p>
...
<footer><a href='{{lang}}/about'>click here</a></footer>
...
</html>
In order to instantiate these “mini-templates”, we thought of using a custom filter:
env.addFilter("finalize", function(input) {
var tmpl = new nunjucks.Template(input),
output = tmpl.render();
return output;
});
with updated main template:
<html>
...
<p>{{ getText("welcome") | finalize }}</p>
...
<footer>{{ getText("about") | finalize }}</footer>
...
</html>
Unfortunately, the filter functions don’t have access to the same context object, so even though the original render("index.html")
has all the variables we need for correct instantiation, the filter function(s) do not, leading to unknown vars simply getting stripped, and vars that were known in res.locals being unknown inside the filter function.
If the filter functions can be made context-aware, so that render calls inside the filter function have the same context object as the “owning” render call, that would be fantastic.
Issue Analytics
- State:
- Created 10 years ago
- Comments:7 (6 by maintainers)
Top GitHub Comments
You need to use
this
, which points to the current Context object. Since you want to get just the raw object, you should use thegetVariables
function.So I’m not sure if I understand this right, but how am I going to set up the filter now after the change?
So the above code when I put that
filter
in say{{ gettext("keyname") | filter }}
the value that is being return it’s still not rendering, so I’m not sure if I’m missing something here.