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_template
to a string containing a template.{% macro my_macro(content) %}
: This defines a macro calledmy_macro
which takes a parameter calledcontent
.{{ my_template|format(content=content) }}
: This uses theformat
filter to render themy_template
variable with thecontent
parameter passed to the macro.{{ my_macro('Hello World!') }}
: This calls themy_macro
macro with the stringHello World!
as thecontent
parameter.
Helpful links
More of Twig
- How to set a session variable in PHP Twig?
- How to use Twig with a PHP MVC framework?
- How to embed YouTube videos in Twig with PHP?
- How to use a Twig file in PHP?
- How to use var_dump with PHP and Twig?
- How to use XOR in Twig with PHP?
- How to check if a string contains a substring in PHP Twig?
- How to use PHP variables in Twig?
- How to use the 'foreach' loop with PHP and Twig?
- How to get a substring in PHP Twig?
See more codes...