问题
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