【问题标题】:Twig highlight word (Timber plugin)Twig 高亮词(Timber 插件)
【发布时间】:2016-12-29 13:01:54
【问题描述】:

我为 Wordpress 使用 Timber 插件。

然后我创建了一个结果搜索页面。我想突出显示用户搜索的单词。

我在 PHP 中写道:

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

然后,用 PHP 替换搜索到的单词:

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

但我不知道如何在 Twig (Timber) 中转换它?

【问题讨论】:

    标签: php twig timber


    【解决方案1】:

    您应该使用自定义树枝过滤器。

    来自文档:extending timber。 (我试图将其改编为您的示例,但您可能需要更改它)

    /* 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);
    }
    

    然后你可以使用你的自定义过滤器

    {{ yourField|highlight(words) }}
    

    【讨论】:

      【解决方案2】:

      您可以使用 Twig 的地图功能简单地突出显示给定的单词:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-13
        • 2014-12-05
        • 2020-08-31
        • 1970-01-01
        相关资源
        最近更新 更多