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, e.g. 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 #}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With