如何在Django模板中突出显示一个字符串

时间:2015-02-26 14:25:21

标签: django templates django-templates highlight

我正在为我的代码编写一个django模板。代码的输出是100行的runlog,所有行都以时间戳开头。 如何编写一个模板,用红色突出显示包含字符串“host to”的所有行? 谢谢!

视图是:

def runlog(request):

     path = request.GET.get('FolderPath')
     chapter_number = request.GET.get('chapter_number')

     content = {'chapter_number': chapter_number}

     title = 'Runlog'
     content = Test(content, path)

return render_to_response('myproject/src/sourcefile.html', {'content': content, 'title': title}, context_instance=RequestContext(request))

输出结果为:

13:46:20: open file file1.TXT
13:46:20: file: run 1
13:46:20: host to A: Deactivate 0
13:46:22: host to A: 0 24 -1 0 0 
13:46:22: A to host: Return=0
##################################

1 个答案:

答案 0 :(得分:1)

Pseduo代码,根据需要进行调整,但您可以使用in运算符来检查字符串是否存在:

<table>
    {% for line in lines %}
    <tr>
        <td class="{% if 'host to' in line.contents %}highlighted{% endif %}"></td>
    </tr>
    {% endfor %}
</table>

有关详细信息,请参阅:https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#in-operator

如果您使用以下方法返回文件内容:

#sample.txt

13:46:20: open file file1.TXT
13:46:20: file: run 1
13:46:20: host to A: Deactivate 0
13:46:22: host to A: 0 24 -1 0 0 
13:46:22: A to host: Return=0

file = open('path/to/sample.txt')
contents = file.readlines()

您将获得每行的列表项:

>>> print contents
>>> ['13:46:20: open file file1.TXT\n', '13:46:20: file: run 1\n',
    '13:46:20: host to A: Deactivate 0\n',
    '13:46:22: host to A: 0 24 -1 0 0\n', '13:46:22: A to host: Return=0\n']

你可以清理一下:

contents = [line.rstrip('\n') for line in contents]

然后你可以在你的Django模板中迭代它:

<ul>
{% for line in contents %}
    <li class="{% if 'host to' in line %}highlighted{% endif %}">{{ line }}</li>
{% endfor %}
</ul>