【问题标题】:replace url in Django template替换 Django 模板中的 url
【发布时间】:2018-03-01 12:38:33
【问题描述】:

{% if shelf.script or shelf.log_url %}
{% if shelf.log_url %}
    Log URL: {{ shelf.log_url }}<br />
{% endif %}
{% if shelf.log_url %}
    <b>Another URL:</b> {{ shelf.log_url.replace("/tmp/BOOTLOG/", "http://www.sxp.com") }}<br />
{% endif %}
{% endif %}

我已经有一个日志 URL,我想用域地址更新这个 URL,并在末尾添加 /index.html。

我想替换这个网址

shelf.log_url 输出 = /tmp/BOOTLOG/darwin_12345.tgz

到这样的事情。

www.sxp.com/darwin_12345/index.html

如何在 Django 模板中进行操作?

【问题讨论】:

  • 为什么需要在模板中做这个?为什么不在视图中,或者在 shelf 上定义一个方法?
  • 显然,视图中的逻辑。最可能的

标签: django python-2.7 django-templates


【解决方案1】:

您尝试做的事情可以通过自定义模板标签来实现。您可以在以下位置找到有关自定义模板标签的更多信息:

https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

【讨论】:

    【解决方案2】:

    您应该为此尝试使用自定义过滤器。你会从Django custom filter documentation得到更好的主意

    例如

    {{shelf.log_url|replace:"url you need"}}
    

    在您的任何文件中添加过滤器,例如 filters.py

    @register.filter(name='replace')
    def replace(url, new_url):
        line = url.replace('/tmp/BOOTLOG/', new_url)
        return line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2014-02-24
      • 2018-03-01
      • 2013-05-04
      • 2010-12-19
      • 2023-03-28
      • 2016-04-20
      • 2011-12-18
      相关资源
      最近更新 更多