如何从Twig中提取从HTML解析的纯文本?

I am making a kind of blog project with Symfony2.

I create the content of my articles with IvoryCKEditorBundle and then display them with {{ article.content|raw }}in Twig.

I want to display on my homepage the first lines of the article: To do this, I need to parse the HTML code and extract strings in it.

How do I extract plain text from HTML, in my Twig template?

Twig offers a bunch of filters that you can use. If you want to display only the first line, you can slice your string after a certain number of characters. You should look into the documentation of Twig. There is also another filter to strip the tags if you need to do it before slicing your string.

{{ '12345'|slice(1, 2) }}
{# outputs 23 #}

http://twig.sensiolabs.org/doc/filters/slice.html

You can get plain text using "striptags" filter then apply "truncate" filter of twig to get portion of your post. for more detail please read my answer https://stackoverflow.com/a/29295738/998686

If you need extra functionality I guess you need to write new twig extension and put any custom logic there. It do not take much time but allows you to do what you want. Have a look at http://symfony.com/doc/current/cookbook/templating/twig_extension.html

  1. 方法1(直接去除)

    {{ "<h2>这是标题</h2>"|striptags }}
    {# 会输出‘这是标题’ #}
    
  2. 方法2(替换去除)

    {{ "<h2>这是标题</h2>"|replace({'<h2>':'','</h2>':''}) }}
    
  1. 方法1(直接去除)

    {{ "<h2>这是标题</h2>"|striptags }}
    {# 会输出‘这是标题’ #}
    
  2. 方法2(替换去除)

    {{ "<h2>这是标题</h2>"|replace({'<h2>':'','</h2>':''}) }}
    {# 会输出‘这是标题’ #}