0

How can i create the global variable in symfony controller like in laravel (example: view()->share('now', date('Y-m-d')); ), that it availiable in all templates?

2

3 Answers 3

1

Setting a global template variable

It is possible to set a global variable available in every template using the addGlobal function in the BaseController class.

$this->get('twig')->addGlobal('today', date('Y-m-d'));

The Twig date functions

Remember that Twig is at its core simply a templating enging for php; it's a skin, an illusion. It replaces the old style <?php echo date('Y-m-d'); ?> commonly used in php. This means two things:

  1. Twig statements are executed server-side
  2. Twig can access (most) php's native function

So in order to set a global variable with today's date, you can imply add the following line:

{% set today = date() %}

If you want to have today be available every template, simply set it in your base.twig.html template. Alternatively you can also use the function only when needed.

Sign up to request clarification or add additional context in comments.

2 Comments

I think that the solution of set it in your base.twig.html is the best. If you only need the date you dont need use the controller to do that. im right?
@Oscar Pretty much, imho using the controller to set a global variable is going the long way around a simple solution
0

Set it as a class property. Eg

class DefaultController extends Controller
{
    private $now = new \DateTime();

    public function page1Action()
    {
        $this->render('...', ['now'=>$this->now]);
    }

    public function page2Action()
    {
        $this->render('...', ['now'=>$this->now]);
    }
}

Comments

0

one possibility is to create variable in session like this.

$session = $this->get('session');
$session->set('var', $my_variable);

in another controller you just get it like this

$session->get('var');

in twig you can get your variable

{% app.session.get('var') %}

it can resolve your issue and it is avalaible for a user not globally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.