PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

[FIXED] How can I define global variables inside a twig template file?

 May 19, 2022     global, php, templating, twig, variables     No comments   

Issue

Is it possible to set global variables in a twig file, so that I can access that variables from other files, macros and blocks.

For example, I want to have variables.twig file and in it set my variables and then I can include it in other templates.

I know that setting global variables is possible from the framework (e.g. Symfony) but I want a solution using twig features only.


Solution

Using Symfony configuration

If you are using Symfony2+, you can set globals in your config.yml file:

# app/config/config.yml
twig:
    # ...
    globals:
        myStuff: %someParam%

And then use {{ myStuff }} anywhere in your application.


Using Twig_Environment::addGlobal

If you are using Twig in another project, you can set your globals directly in the environment:

$twig = new Twig_Environment($loader);
$twig->addGlobal('myStuff', $someVariable);

And then use {{ myStuff }} anywhere in your application.


Using a Twig template

When you're including a piece of Twig code, you're only including the rendered view coming from that code, not the code itself. So it is by design not possible to include a set of variables the way you are looking for.



Answered By - Alain Tiemblo
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing