twigHow to use yield in Twig with PHP?
Yield in Twig with PHP can be used to create a template that can be reused in multiple places. It allows you to create a template that can be used to render a specific part of a page.
Example code
{% set my_template = '<div>{{ content }}</div>' %}
{% macro my_macro(content) %}
{{ my_template|format(content=content) }}
{% endmacro %}
{{ my_macro('Hello World!') }}
Output example
<div>Hello World!</div>
Code explanation
{% set my_template = '<div>{{ content }}</div>' %}: This sets a variable calledmy_templateto a string containing a template.{% macro my_macro(content) %}: This defines a macro calledmy_macrowhich takes a parameter calledcontent.{{ my_template|format(content=content) }}: This uses theformatfilter to render themy_templatevariable with thecontentparameter passed to the macro.{{ my_macro('Hello World!') }}: This calls themy_macromacro with the stringHello World!as thecontentparameter.
Helpful links
More of Twig
- How to use the 'for' loop with PHP and Twig?
- How to embed YouTube videos in Twig with PHP?
- How to parse XML in Twig with PHP?
- How to use a PHP function in Twig?
- How to check if a string contains a substring in PHP Twig?
- How to integrate Twig with Yii2?
- How to use Twig in PHP to get the current year?
- How to get a substring in PHP Twig?
- How to call an object method in Twig and PHP?
See more codes...