【问题标题】:Django. Use url tags inside quotes, inside quotes姜戈。在引号内使用 url 标签,在引号内
【发布时间】:2014-07-13 13:44:27
【问题描述】:

我想将这个变量传递给上下文并渲染它,它包含html标签。

notificacion_string = "<a href = \"{% url \'perfiles:perfil\' actor.usuario.username  \'recientes\' %}\" > %s </a> voted on your post" % (notificacion.actor.usuario.username)

如您所见,我已尝试转义 href=" " 中的引号。但我得到这个错误:

%u format: a number is required, not unicode

所以,我猜在评估 "% url .." %() 时会发生错误。我尝试了很多事情都没有成功。

额外信息:

url "pefiles:perfil" 接收两个参数:

 url(r'^(?P<username>\w+)/(?P<queryset>\w+)/$',views.perfil, name='perfil'),

参数是用户名和查询集,第一个来自notificacion.actor.usuario.username,第二个是字符串'recientes'。

提前感谢您的帮助。

【问题讨论】:

    标签: django url tags escaping quotes


    【解决方案1】:

    没有必要逃避任何这些引号。评估模板标签内代码的上下文与周围的 HTML 完全分开,因此它们不会干扰。

    【讨论】:

    • 我仍然收到错误“%u 格式:需要一个数字,而不是 unicode”。我猜问题是 "%s"%(...): the "% url" is read as a带有无符号十进制替换的字符串。我不知道如何解决它。感谢您提供关于引号的提示。
    【解决方案2】:

    {% url ... %} 是一种模板机制。不要尝试从模板外部使用它。相反,在视图中做你自己会做什么:

    在视图中生成 URL

    from django.core.urlresolvers import reverse
    
    # Generate the URL using the Django urlresolver reverse
    url = reverse('perfiles:perfil', kwargs={'username': actor.usuario.username, 'queryset': 'recientes' })
    
    # Then concatenate the URL as other string argument
    notificacion_string = "<a href ='%s'> %s </a> voted on your post" % (url, notificacion.actor.usuario.username)
    

    官方的 Django 文档解释得很好,所以我建议你查看Django URLresolvers

    为了比较,这里有另外两种生成链接的方式(与您的问题无关):

    在模板 (HTML) 中生成 URL

    <a href = "{% url 'perfiles:perfil' actor.usuario.username  'recientes' %}" >{{notificacion.actor.usuario.username}}</a> voted on your post"
    

    在模板中用 jQuery 生成 URL

    <script>
        // Generate an URL with a fake username
        var url = "{% url 'perfiles:perfil' 'FakeUsername'  'recientes' %}"
    
        // Let's supose we received an AJAX response with a variable username
        username = response['username']
    
        // Replace the string 'FakeUsername' for the real one
        url = url.replace('FakeUsername', username)
    </script>
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 2016-05-27
      • 2012-02-21
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      相关资源
      最近更新 更多