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 use a Twig file in PHP?
- Where can I convert PHP to Twig online?
- How to use a PHP function in Twig?
- How to check if a string contains a substring in PHP Twig?
- How to use Twig in PHP to get the current year?
- How to use Slim/Twig-View in PHP?
- How to use PHP variables in Twig?
- How to use the Twig library with PHP?
- How to use a switch case in PHP Twig?
See more codes...