Twig 高亮单词(Timber 插件)

问题描述 投票:0回答:3

我使用 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
3个回答
2
投票

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

来自文档:延伸木材。 (我尝试将其适应您的示例,但您可能需要更改它)

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

1
投票

您可以使用 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(' ') }}

0
投票

您可以通过创建自定义树枝扩展来做到这一点:

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

在模板中:

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

不要忘记“原始”过滤器以使其发挥作用。

© www.soinside.com 2019 - 2024. All rights reserved.