2016-12-01 68 views
0
from django import template 
from django.template import engines 
from django.utils.html import format_html 

register = template.Library() 
@register.simple_tag 
def external_link(link): 
    ''' 
    Creates an anchor tag 
    ''' 
    return format_html('<a target="_blank" href="%s"> Some External Link </a>' % (link)) 

link = '{% external_link https://stackoverflow.com %}' 
template_context = '<div> {{ a_link }} </div>' 
template = engines['django'].from_string(template_context) 
template.render({ 
    'a_link': link, 
}) 

电流输出:u'<div> {% external_link https://stackoverflow.com %} </div>'从变量解析Django模板语言代码

我需要的是:u'<div> <a target="_blank" href="https://stackoverflow.com"> Some External Link </a> </div>'

如何通过保持模板代码中的变量link实现这一目标?

+0

这是什么标签实现的一部分吗?为什么不直接把链接直接放入? – Sayse

+0

我使用这个的上下文是逻辑是不同的,但我已经剥离了代码,我面临的问题... – NEB

+0

我真的不能尝试它,但我想你需要''

{}
'.format(link)' – Sayse

回答

2

问题是,您传递的字符串将作为上下文变量呈现,而不是您要呈现的模板的一部分。

只是简单地包括标签的模板字符串

template_context = '<div>{}</div>'.format(link)