【问题标题】:How to highlight a String in Django Template如何在 Django 模板中突出显示字符串
【发布时间】:2015-04-28 23:26:21
【问题描述】:

我正在为我的代码编写一个 django 模板。代码的输出是 100 行的运行日志,所有行都以时间戳开头。 如何编写一个模板,以红色突出显示包含字符串“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
##################################

【问题讨论】:

  • 这是一个非常广泛的问题。您可以编写自定义模板过滤器或编写一些客户端 (JavaScript) 代码。
  • 谢谢!我想我将不得不使用自定义模板
  • Test(content, path) 返回什么?
  • 另外,添加模板代码,而不是渲染模板的代码。
  • Test(content, path) 返回数百行的运行日志。

标签: django templates django-templates highlight


【解决方案1】:

伪代码,根据需要进行调整,但您可以使用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>

【讨论】:

  • 谢谢!我已经尝试过类似的东西,但由于某种原因没有突出显示。
  • 是的,@bush 请发布返回数据的视图,以及您已经尝试过的模板代码。
  • 我使用的模板代码与@Brandon 相同,但 for 循环不同: {% for string in lines %} ,可能是错误的方法
猜你喜欢
  • 2013-12-17
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2017-04-26
  • 2023-03-14
  • 2017-10-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多