Twig highlight word (Timber plugin)

老子叫甜甜 提交于 2019-12-11 06:14:23

问题


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) ?


回答1:


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) }}



回答2:


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(' ') }}


来源:https://stackoverflow.com/questions/41380302/twig-highlight-word-timber-plugin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!