Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Variables in base.html.twig

Tags:

php

twig

symfony

I'm wondering how I would go about using custom variables in base.html.twig in a symphony application.

I know I can use {{ app.whatever }} but how would I use {{ myvariable }} or {{ myentity.row }} if I wanted to?

Thanks

like image 712
Jeremy Avatar asked Oct 30 '25 04:10

Jeremy


1 Answers

As a variable is rendered with a twig template, you can use this variable in both parent and child templates.

In other words, if you have the following base template:

// base.html.twig
<html>
    <body>
       {{ block body }} 
       {{ endblock }}
    </body>
</html>

The following child template:

// child.html.twig
{% extends 'base.html.twig' %}
{% block body %}
    // content
{% endblock %}

And the following controller action:

public function renderVariableAction()
{
    return $this->render('child.html.twig', [
        'hello' => 'Hello world',
    ]);
}

You can use {{ hello }} in both base.html.twig and child.html.twig.

EDIT

For a global variable:

// app/config/config.yml
# ...

twig:
    # ...
    globals:
        your_custom_var: "your_value"

You can't define a variable that is always assigned to a specific template, the variable must be rendered with it dynamically.

Note You can define global variables dynamically like this:

$this->get('twig')->addGlobal('entity', $entity);

So you can easily inject the same variable on kernel.response using an EventListener.

See global variables in templates.

like image 194
chalasr Avatar answered Nov 01 '25 18:11

chalasr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!