Imagine we already had a page.title variable in context, and we could access it through {{ page.title }}. Would be cool if we could define a variable in the context on the fly:
{{ title = page.title }}
<!-- we can now use {{ title }} instead of {{ page.title }} -->
Title is {{ title }}
Currently, that outputs:
undefined
Title is [value of title]
Right now, it does kinda work, but it still outputs undefined where we've set the variable, as I've explained above.
Maybe we could use const to identify that we want to set a variable in context:
{{ const title = page.title }}
Title is {{ title }}
Result:
Title is [value of title]
This would be really useful when you need to access a deeply nested object and you can't use a scope (like inside attributes).
Nunjucks does it with a set keyword, they allow you to define a variable like this:
<p>{{ username }}</p>
{% set username = "Joe" %}
<p>{{ username }}</p>
If username was initially 'James', this would print:
What do you think?
Imagine we already had a
page.titlevariable in context, and we could access it through{{ page.title }}. Would be cool if we could define a variable in the context on the fly:{{ title = page.title }} <!-- we can now use {{ title }} instead of {{ page.title }} --> Title is {{ title }}Currently, that outputs:
Right now, it does kinda work, but it still outputs
undefinedwhere we've set the variable, as I've explained above.Maybe we could use
constto identify that we want to set a variable in context:{{ const title = page.title }} Title is {{ title }}Result:
This would be really useful when you need to access a deeply nested object and you can't use a scope (like inside attributes).
Nunjucks does it with a
setkeyword, they allow you to define a variable like this:If
usernamewas initially 'James', this would print:What do you think?