【问题标题】:Django - How do I use the URL template tag in a format_html safe string?Django - 如何在 format_html 安全字符串中使用 URL 模板标签?
【发布时间】:2017-03-02 19:55:29
【问题描述】:

我正在尝试将 URL 模板标记包含在使用 format_html 方法创建的字符串中:

message = format_html(
            '''<div>
               <p>{0} wants to join {1}!</p>
               {% url 'accounts:detail' pk={2} as profile_url %}
               <p>
               View their
               <a href="{{ profile_url }}">profile</a>
               </p>
               <div>Approve</div>
               <div>Deny</div>
               </div>
           ''',
           self.request_user.username,
           self.lab.name,
           self.request_user.pk)

输出到浏览器的html是这样的:

<a href="{ url 'accounts:detail' pk=4}">profile</a>

基本上我的 url 标签没有 %'s。

我尝试通过键入以下内容来转义 %:

{%% url 'accounts:detail' pk={2} as profile_url %%}

但我收到相同的输出。

有什么想法吗?

【问题讨论】:

  • 您为什么选择使用 format_html?为什么不把它放在一个实际的模板中?

标签: python django templatetags


【解决方案1】:

你可以直接用reverse()创建网址:

message = format_html(
        '''<div>
           <p>{0} wants to join {1}!</p>
           <p>
           View their
           <a href="{2}">profile</a>
           </p>
           <div>Approve</div>
           <div>Deny</div>
           </div>
       ''',
       self.request_user.username,
       self.lab.name,
       reverse('accounts:detail', kwargs={'pk':self.request_user.pk})
)

【讨论】:

    【解决方案2】:

    您可能应该尝试使用 {{ profile_url|safe }} 或使用{% autoescape %} Autoescappe

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2012-02-02
      • 2019-11-26
      • 2010-09-20
      • 1970-01-01
      • 2020-07-19
      相关资源
      最近更新 更多