【问题标题】:<a></a> tags not being rendered when put in quotes<a></a> 标签放在引号中时未呈现
【发布时间】:2015-01-18 03:18:17
【问题描述】:

我知道这是一个微不足道的错误,但我无法调试它。
当我将标签放在引号中并为链接动态生成字符串时,不会生成“链接”。而是按原样呈现''。 (我正在尝试在 GAE 中运行一个使用 django 模板框架的 python 脚本)

以下是我的代码:

from google.appengine.ext.webapp import template  

...  

html = html + template.render('templates/footer.html',
                                          {'links': 'Enter <a href="/">another sighting</a>.'})  

以下是模板中的'footer.html':

<p>
{{ links }}
</p>
</body>
</html>  

以下是输出:

任何帮助将不胜感激。 (Firefox 和 Google Chrome 都是这种情况)

【问题讨论】:

    标签: python html django google-app-engine


    【解决方案1】:

    safe 过滤器添加到您的变量中:

    {{ links|safe }}
    

    或者使用mark_safe函数在python代码中将你的字符串标记为安全:

    from django.utils.safestring import mark_safe
    
    html = html + template.render('templates/footer.html',
                {'links': mark_safe('Enter <a href="/">another sighting</a>.')})  
    

    这是 django 的 automatic HTML escaping 机制。您可以使用autoescape 模板标签来控制它,但我不建议这样做:-)

    【讨论】:

    • 谢谢!有效!但为什么它第一次不起作用,即我写它的方式? (我实际上指的是一个相同的教程,并且它工作,虽然它使用的是 Python 2.5 的 GAE 教程,而我的是 2.7)
    • 这是 django 最酷的功能之一。在此处阅读文档:docs.djangoproject.com/en/1.7/topics/templates/…
    猜你喜欢
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2017-06-08
    • 2016-03-31
    相关资源
    最近更新 更多