symfony 2 twig limit the length of the text and put three dots

前端 未结 13 2026
太阳男子
太阳男子 2021-01-30 00:36

How can I limit the length of the text, e.g., 50, and put three dots in the display?

{% if myentity.text|length > 50 %}

{% block td_text %} {{ myentity.text}         


        
13条回答
  •  情歌与酒
    2021-01-30 00:55

    I wrote this simple marco for the same purpose, hope it helps:

    {%- macro stringMaxLength(str, maxLength) -%}
        {%- if str | length < maxLength -%}
            {{ str }}
        {%- else -%}
            {{ str|slice(0, maxLength) }}...
        {%- endif -%}
    {%- endmacro -%}
    

    Usage Example #1 (Output: "my long string here ..."):

    {{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}
    

    Usage Example #2 (Output: "shorter string!"):

    {{ _self.stringMaxLength("shorter string!", 20) }}
    

提交回复
热议问题