Twig highlight word (Timber plugin)

1.3k Views Asked by At

I use Timber plugin for Wordpress.

And I create a results search page. I would like to highlight the word that the user searched.

In PHP I wrote that :

$highlight = array();
if ($terms) {
    foreach($terms as $term) {
        array_push($highlight, '<span class="blue bold">'.$term.'</span>');
    }
}

And that, to replace the searched word in PHP :

<p class="date red"><?php echo str_ireplace($terms, $highlight, get_field('subtitle_post')); ?></p

But I don't know how to transform that in Twig (Timber) ?

3

There are 3 best solutions below

0
On

You should use a custom twig filter.

From the documentation: extending timber. (I tried to adapt it to your example but you might need to change it)

/* functions.php */

add_filter('get_twig', 'add_to_twig');

function add_to_twig($twig) {
    /* this is where you can add your own fuctions to twig */
    $twig->addExtension(new Twig_Extension_StringLoader());
    $twig->addFilter(new Twig_SimpleFilter('highlight', 'highlight'));
    return $twig;
}

function highlight($text, array $terms) {

    $highlight = array();
    foreach($terms as $term) {
       $highlight[]= '<span class="blue bold">'.$term.'</span>';
    }

    return str_ireplace($terms, $highlight, $text);
}

Then you could use your custom filter with

{{ yourField|highlight(words) }}
0
On

You can simply highlight given words with Twig's map function:

{% set sentence = 'The quick brown fox jumps over the lazy dog' %}
{% set highlight = ['the', 'quick', 'fox'] %}
{{ sentence|split(' ')|map( word => ( word|lower in highlight ? '<strong>' ~ word ~ '</strong>' : word ) )|join(' ') }}
0
On

You can do that by creating a custom twig extension :

// src/Twig/AppExtension.php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class HighlightExtension extends AbstractExtension
{

public function getFilters()
{
    return [
        new TwigFilter('highlight', [$this, 'highlightSearchTerms']),
    ];
}

public function highlightSearchTerms($text, $searchTerms)
{
    // Échappe les caractères spéciaux pour éviter les problèmes de regex
    $escapedTerms = array_map('preg_quote', $searchTerms);
    
    // Crée une expression régulière pour chaque terme de recherche
    $pattern = '/(' . implode('|', $escapedTerms) . ')/i';

    // Utilise la regex pour mettre en surbrillance les termes de recherche
    $highlightedText = preg_replace($pattern, '<span class="highlight">$1</span>', $text);

    return $highlightedText;
}

In the template :

{% set highlight = ['word1','word2'] %}
{{ article.content|highlight(highlight)|raw  }}

Don't forget the 'raw' filter to make it work.