1

我在 twig 中使用以下函数来显示保存在数据库中的新闻项目描述的部分内容:

{{ new.description|striptags|truncate(300,true)|raw|nl2br }}

使用 html 元素中的这个函数p,我得到字符不超过 300 的文本,然后我添加了一个元素“阅读更多” a

<p >{{  new.description|striptags|truncate(200,true)|raw|nl2br }}
  <a class="href_blue" href="{{ path('new', {'id': new.id}) }}">
  <strong> [Read More] </strong></a>
</p>

此代码适用于包含超过 300 个字符的段落中的文本,但例如,如果我有另一个带有几个“p”元素的文本,然后在 twig 中更改为
元素,我需要它只显示几行,因为我有显示它的容器的最大高度,我不知道该怎么做,因为它会显示所有换行符,直到它不超过 300 个字符。

为了更清楚一点,我显示了结果的图像: 在此处输入图像描述

我需要的是,在 Title2 有很多换行符的情况下,只需显示一些并在之前添加“阅读更多”,以便 div 的高度等于前一个(显示示例我删除了 max-Height和溢出:隐藏)。

我怎么能得到那个?

我提前向您的帮助致意。

4

1 回答 1

1

你可以在 Twig 中做这样的事情:

{% set paragraphs = new.description|split('</p>') %}
{% set summary = '' %}
{% for i in 1..10 %}
    {% set summary = summary ~ paragraphs[i] %}
{% endfor %}

{% set summary = summary ~ '[Read More]' %}

现在您可以使用summarytwig 文件中的变量来显示截断的摘要。

根据评论编辑#2

然后试试这个:

{% set paragraphs = new.description|split('</p>') %}
{% set summary = '' %}
{% for i in 1..(paragraphs|length) %}
    {% set summary = summary ~ paragraphs[i] %}
    {% if summary|length > 300 %}
        {% set shortsummary = summary %}
    {% endif %}
{% endfor %}

{% set final_summary = shortsummary|slice(:300) ~ '[Read More]' %}

编辑#3 代码修改为问题的解决方案

{% set paragraphs = new.description|striptags|truncate(300,true)|raw|nl2br %}

{% set paragraphs = paragraphs|split('<br />') %}

{% set summary = "" %}
{% set cont = 90 %}
{% set type = "" %}

{% if paragraphs|length == 1 %}
   {% set summary =  paragraphs[0] %}
   {% if summary|length <= 300 %}
      {% set type = "" %}
   {% else %}
      {% set type = "anything" %}
   {% endif %}
{% else %}
   {% for i in 1..(paragraphs|length) %}
      {% if summary|length + cont + paragraphs[i-1]|length  <= 500 %}
          {% set summary = summary  ~ "<br>" ~ paragraphs[i-1] %}
          {% set cont = cont + 90 %}
      {% else %}
          {% set type = "anything" %}
      {% endif %}
   {% endfor %}
{% endif %}

//In the case of a description with less than 300 characters the option "Read More" is not shown
{% if type != "" %}
  <p>{{ summary|striptags|truncate(300,true)|raw|nl2br }}<a class="href_blue" href="{{ path('new', {'id': new.id}) }}"> <strong> [Read More] </strong></a></p>
{% else %}
  <p>{{ summary|striptags|truncate(300,true)|raw|nl2br }}<a class="href_blue" href="{{ path('new', {'id': new.id}) }}"></a></p>
{% endif %}
于 2017-01-16T20:30:48.163 回答