突出显示搜索的单词

时间:2015-07-17 00:39:41

标签: php symfony twig

在Symfony2中,我如何从搜索框中突出显示我搜索的单词:

//搜索Twig:

{% block body -%}
    <h1>Results of "{{ find }}"</h1>
    {% if entities%}
        {% for entity in entities %}
            <table class="record_properties">
                <tbody>
                    <tr>            
                        <td>><a href="{{ path('onequestion_show', { 'id': entity.id }) }}">{{ entity.question }}</a></td>
                    </tr>                 
                </tbody>
            </table>
        {% endfor %}
    {%else%}
        <td>No Results found</td>
    {%endif%}

{% endblock %} 

// searchController:

public function searchAction() {

        $request = $this->getRequest();
        $data = $request->request->all();
        $find = $data['search'];

        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
                        'SELECT p.id, p.question
        FROM EpitaEpitaBundle:questionanswer p
        WHERE p.question LIKE :data')
                ->setParameter('data', "%$find%");


        $res = $query->getResult();


        return $this->render('EpitaEpitaBundle:questionanswer:search.html.twig', array(
                    'entities' => $res,
                    'find' => $find));
    }

//我收到了搜索结果,但我希望它能突出显示......

2 个答案:

答案 0 :(得分:2)

你可能会做类似的事情:


java      9645 9863     ubuntu  133u     IPv4              19375      0t0    TCP ip-10-20-187-89:51548->ec2-100-200-86-25.compute-1.amazonaws.com:https (CLOSE_WAIT)
java      9645 9864     ubuntu  133u     IPv4              19375      0t0    TCP ip-10-20-187-89:51548->ec2-100-200-86-25.compute-1.amazonaws.com:https (CLOSE_WAIT)
java      9645 9865     ubuntu  133u     IPv4              19375      0t0    TCP ip-10-20-187-89:51548->ec2-100-200-25.compute-1.amazonaws.com:https (CLOSE_WAIT)
java      9645 9902     ubuntu  133u     IPv4              19375      0t0    TCP ip-10-20-187-89:51548->ec2-100-200-25.compute-1.amazonaws.com:https (CLOSE_WAIT)

然后在css中创建一个类:

<td>><a href="{{ path('onequestion_show', { 'id': entity.id }) }}">{{ entity.question|replace({find: "<span class='highlight'>" ~ find ~ "</span>"}) }}</a></td>

另一种选择是用PHP编写自己的过滤器。

答案 1 :(得分:0)

我建议您根据@Mindastic的建议创建自己的过滤器。

为此你需要一个自定义的Twig扩展名,按照this cookbook entry进行操作。

您需要将输出标记为safe HTML才能使其正常工作。

最后但并非最不重要的是,出于安全原因,我建议您在输入值上使用PHP strip_tags()函数以避免注入。

相关问题