简体   繁体   中英

Twig: How to display html content in the block title

In my symfony2 project, I have some twig temlates. In one of them, I have the block title.

{% block title %}{{ announcement.title }}{% endblock %}

The problem is that the variable {{ announcement.title }} can be: <em>test</em>

In this case, my title will be <em>test</em> and it needs to be

test

I have tryied the {% block title %}{{ announcement.title|raw }}{% endblock %} but nothing changed. This is only in the block title, if I put the raw filter in my block content, then it is fine.

Any idea on how to do that ?

EDIT:

Here is an example:

{% block title %}{{ announcement.title|raw }}{% endblock %}
{% block body_announcements %}{{ announcement.title|raw }}{% endblock %}

In the block title, I see <em>test<em> and in the block body_announcements I see test which is right.

You have to use the raw filter to display text and tags as is :

{% block title %}{{ announcement.title|raw }}{% endblock %}

Edit: The striptags filter is used to display text without the tags:

{% block title %}{{ announcement.title|striptags }}{% endblock %}

Example

Twig code

{% set str = '<em>test</em>' %}
1: {{ str }}
2: {{ str|raw }}
3: {{ str|striptags }}

Result

1: <em>test</em>

The <em></em> tag is escaped.

2: test

The <em></em> tag is displayed and interpreted by the browser.

3: test

The <em></em> tag is removed, only the text is shown.

你可以这样做来逃避HTML

{% block title %}{{ announcement.title|e('html') }}{% endblock %}

试试以下......

{% block title %}{{ announcement.title|raw }}{% endblock %}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM