Skip to content

Commit 17ae545

Browse files
wouterjweaverryan
authored andcommitted
Documented services as global vars
1 parent 8e5caca commit 17ae545

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

cookbook/templating/global_variables.rst

+46-3
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,50 @@ Now, the variable ``ga_tracking`` is available in all Twig templates:
4141

4242
<p>The google tracking code is: {{ ga_tracking }}</p>
4343

44-
It's that easy! You can also take advantage of the built-in :ref:`book-service-container-parameters`
44+
It's that easy!
45+
46+
Referencing Services
47+
--------------------
48+
49+
Instead of using static values, you can also set the value to a service.
50+
Whenever the global variabele is accessed in the template, the service will be
51+
requested from the service container and you get access to that object.
52+
53+
This is done by prefixing the string with ``@``, which you already know from
54+
injecting a service:
55+
56+
.. configuration-block::
57+
58+
.. code-block:: yaml
59+
60+
# app/config/config.yml
61+
twig:
62+
# ...
63+
globals:
64+
user_management: "@acme_user.user_management"
65+
66+
.. code-block:: xml
67+
68+
<!-- app/config/config.xml -->
69+
<twig:config ...>
70+
<!-- ... -->
71+
<twig:global key="user_management">@acme_user.user_management</twig:global>
72+
</twig:config>
73+
74+
.. code-block:: php
75+
76+
// app/config/config.php
77+
$container->loadFromExtension('twig', array(
78+
// ...
79+
'globals' => array(
80+
'user_management' => '@acme_user.user_management',
81+
),
82+
));
83+
84+
Using Service Container Parameters
85+
----------------------------------
86+
87+
You can also take advantage of the built-in :ref:`book-service-container-parameters`
4588
system, which lets you isolate or reuse the value:
4689

4790
.. code-block:: yaml
@@ -77,8 +120,8 @@ system, which lets you isolate or reuse the value:
77120
78121
The same variable is available exactly as before.
79122

80-
More Complex Global Variables
81-
-----------------------------
123+
Using a Twig Extension
124+
----------------------
82125

83126
If the global variable you want to set is more complicated - say an object -
84127
then you won't be able to use the above method. Instead, you'll need to create

0 commit comments

Comments
 (0)