Search code examples
phphtmltexttwig

How to display HTML in twig whilst still trimming the length of what is displayed


I am displaying a block of rich text inside a twig page using:

{{ log.entry | raw }}

This displays it in the rich text format, however I was previously only displaying the first 50 characters of this using

{{ log.entry[:50] ~ '...'}}

When I combine the two in either of the below formats:

{{ log.entry[:50] ~ '...' | raw }}


{{ log.entry | raw [:50] ~ '...'}}

It displays it in the none html formatted way. Any thoughts on how to go about displaying around 50 characters of the text in its rich text format using twig?


Solution

  • Twig is only a templating engine, it will not do what you want. What you need to do is change the data you are feeding it.

    Assuming Log.entry is a method which returns the entire log string, you could create a similar method, lets say Log.entry_50 that returns 50 characters minimum until the first closing tag is encountered. (Assuming you would want to be able to display the entire string, not just the first 50 characters)

    Convenient assumption: all closing tags are the same, let's say </X>. In your method entry_50, take the string from entry and do the following:

    // assuming $entry holds the entire string 
    $closing_tag = '</X>';
    $end = strpos($entry, $closing_tag, 49) + 4; //add 4 because you want to include te entire closing tag
    return substr($entry,0,$end);
    

    Now do {{ Log.entry_50 | raw }} in your twig template.

    Little less convenient assumption:

    Here I will assume not all closing tags are the same, but all have the form of </*>.

    // assuming $entry holds the entire string
    $closing_tag_beginning = '</';
    $closing_tag_end = '>';
    $end_start = strpos($entry, $closing_tag_beginning, 49);
    $end_end = strpos($entry, $closing_tag_end, $end_start); 
    return substr($entry,0,$end_end);
    

    Ofcourse it will be a slightly different solution if Log.entry is a variable, but in that case just add methods which incorporate above solution.