@@ -60,8 +60,8 @@ Twig Extensions
60
60
61
61
.. best-practice ::
62
62
63
- Define your Twig extensions in the ``AppBundle/Twig/ `` directory. Your
64
- application will automatically detect them and configure them .
63
+ Define your Twig extensions in the ``AppBundle/Twig/ `` directory and
64
+ configure them using the `` app/config/services.yml `` file .
65
65
66
66
Our application needs a custom ``md2html `` Twig filter so that we can transform
67
67
the Markdown contents of each post into HTML.
@@ -73,11 +73,21 @@ a new dependency of the project:
73
73
74
74
$ composer require erusev/parsedown
75
75
76
- Then, create a new ``Markdown `` class that will be used later by the Twig
77
- extension. It just needs to define one single method to transform
76
+ Then, create a new ``Markdown `` service that will be used later by the Twig
77
+ extension. The service definition only requires the path to the class:
78
+
79
+ .. code-block :: yaml
80
+
81
+ # app/config/services.yml
82
+ services :
83
+ # ...
84
+ app.markdown :
85
+ class : AppBundle\Utils\Markdown
86
+
87
+ And the ``Markdown `` class just needs to define one single method to transform
78
88
Markdown content into HTML::
79
89
80
- namespace AppBundle\Service ;
90
+ namespace AppBundle\Utils ;
81
91
82
92
class Markdown
83
93
{
@@ -97,14 +107,14 @@ Markdown content into HTML::
97
107
}
98
108
99
109
Next, create a new Twig extension and define a new filter called ``md2html ``
100
- using the ``Twig_SimpleFilter `` class. Inject the newly defined ``Markdown ``
101
- class in the constructor of the Twig extension:
110
+ using the ``Twig_SimpleFilter `` class. Inject the newly defined ``markdown ``
111
+ service in the constructor of the Twig extension:
102
112
103
113
.. code-block :: php
104
114
105
115
namespace AppBundle\Twig;
106
116
107
- use AppBundle\Service \Markdown;
117
+ use AppBundle\Utils \Markdown;
108
118
109
119
class AppExtension extends \Twig_Extension
110
120
{
@@ -137,11 +147,18 @@ class in the constructor of the Twig extension:
137
147
}
138
148
}
139
149
140
- And that's it!
150
+ Lastly define a new service to enable this Twig extension in the app (the service
151
+ name is irrelevant because you never use it in your own code):
152
+
153
+ .. code-block :: yaml
141
154
142
- Your application will :ref: `autoconfigure <services-autoconfigure >` your twig
143
- extension and inject a ``Markdown `` instance in it thanks to
144
- :doc: `autowiring </service_container/autowiring >`.
155
+ # app/config/services.yml
156
+ services :
157
+ app.twig.app_extension :
158
+ class : AppBundle\Twig\AppExtension
159
+ arguments : ['@app.markdown']
160
+ public : false
161
+ tags : [twig.extension]
145
162
146
163
.. _`Twig` : http://twig.sensiolabs.org/
147
164
.. _`Parsedown` : http://parsedown.org/
0 commit comments