In Smarty you can do
{$var = 'bla' scope=parent}
Is it possible in Twig?
Don't suggest to use blocks. I know. I need variable.
In Smarty you can do
{$var = 'bla' scope=parent}
Is it possible in Twig?
Don't suggest to use blocks. I know. I need variable.
You can use the following in your child pages:
@n3xus gave a nice answer, it actually helped me also (thanks), but you may also want to take a look at this page from the documentation: Twig docs
One particularly nice feature is the ability to set a chunk of text/html:
Makes it easy to generate very specific bits of content from the child templates.
A great way to do something like this i just discovered:
parent.twig
child.twig
if your child template does not define the block
subvar
, the variable inparent.twig
will be empty.If you don't want to use the
default()
filter (i.e., when you want to use the variable multiple times throughout your parent and child templates), you can actually define a block that contains your entire page in the parent template, and then nest your other blocks inside of that:You can then override the
page
variable in thepage
block in your child template, by setting the value and then callingparent()
:Note that in the parent template, we define the
page
variable outside of thepage
block, while in the child template we define it inside thepage
block.So, Twig will do the following:
child.twig
, it will start from the top ofbase.twig
, setting the default values for thepage
variable.page
block, it will see thatchild.twig
overrides that block. So, it will run thepage
block inchild.twig
instead.page
block inchild.twig
, it will set the new values for thepage
variable. It will then callparent()
, which tells it to go back tobase.twig
and render the parentpage
block.child.twig
(in my example, it will render thecontent
block).See a working example here. Do be aware that this can become more complicated when you start adding multiple layers of inheritance (e.g., grandchild templates).
Use set tag with embed
Example:
parent.twig:
child.twig:
If you simply want a variable to be 'overridable' from a subtemplate you can set your variable in the parent like so:
So you could set up a situation like this...
base.twig
parent.twig
child.twig
The end result will be:
I think that works nicely for most situations. Rather than forcing the parent var to be overridden by the child, the parent 'lets' the variable be overridden by children. You could also define different behaviour in the parent such as concatenation rather than overriding.