In twig templating, is it possible to append content to a block?
For example, consider the template files below.
layout.html.twig
<html>
<head>
<style>
{% block css %}{% endblock css %}
</style>
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>
inner.html.twig
{% block css %}
a { color: #fff; }
body { background: #f00; }
{% endblock css %}
{% block content %}
Some contents here...
{% include 'myWidget.html.twig' %}
{% endblock content %}
myWidget.html.twig
{% block css %}
div a { color: #777; }
{% endblock css %}
{% block content %}
<div><a>myWidget content here...</a></div>
{% endblock content %}
Notice the block css.. What I am trying to accomplish is that I want to have each content of the block css appended to the layout.html.twig's css block. Thus, the end result should be:
<html>
<head>
<style>
a { color: #fff; }
body { background: #f00; }
div a { color: #777; }
</style>
</head>
<body>
Some contents here...
<div><a>myWidget content here...</a></div>
</body>
</html>
This should do the trick:
{% block css %}
{{ parent() }}
div a { color: #777; }
{% endblock css %}
{% block content %}
<div><a>myWidget content here...</a></div>
{% endblock content %}
Shortcut to append/prepend content to blocks with few content, eg a pagetitle
base.html.twig
...
<title>{% block title %}MyApp{% endblock %}</title>
...
template extending base layout
{% extends '::base.html.twig' %}
{% block title 'Page1 - '~parent() %} {# prepend #}
{% block title parent()~' - Page1' %} {# append #}
Calling parent() in the child template works, but each child must explicitly accept inheritance from the parent. You can also choose to enforce this inheritance by using a sub-block instead.
inner.html.twig
{% block css %}
a { color: #fff; }
body { background: #f00; }
{% block css_custom %}{% endblock css_custom %}
{% endblock css %}
myWidget.html.twig
{% block css_custom %}
div a { color: #777; }
{% endblock css_custom %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.