1

所以在我的template,我有以下代码:

<span class="state-txt">{{ state }}</span>

在我views.py的 中,它使用以下 if/else 循环处理:

if user is not None:
            if user.is_active:
                login(request, user)            
                state = "You're successfully logged in!"
                return render_to_response('uc/portal/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request))
            else:
                state = "Your account is not active, please contact UC admin."
        else:
            state = "Your username and/or password were incorrect."

本质上,它目前工作正常,但我希望每个标签state都能够包含不同的 < img> 标签,但是当我只键入state = "<img src="some.jpg"> Your username and/or password were incorrect."html 时无法正确呈现。有什么方法可以做我想要在 Django 中做的事情,还是我在叫错树?

4

3 回答 3

2

我只会在视图的上下文中传递图像 URL,然后在模板中使用它。像这样的东西:

if user:
    if user.is_active:
        login(request, user)            
        state = "You're successfully logged in!"
        state_img = success_image_url
        return render_to_response('uc/portal/index.html', 
                 {'state': state, 
                  'state_img': state_img, 
                  'username':username
                 }, context_instance=RequestContext(request))
    else:
        state_img = inactive_image_url
        state = "Your account is not active, please contact UC admin."
else:
    state_img = invalid_credentials_url
    state = "Your username and/or password were incorrect."

并在模板中

<span class="state-txt">
    <img src="{{state_img}}" />{{ state }}
</span>
于 2013-08-08T20:58:46.713 回答
1

为了完整起见,karthikr 已经发布了一个很好的解决方案:

html 无法正确呈现的原因是因为 Django 模板语言自动假定所有输出 by{{ ... }}是不安全的,所有在 HTML 中具有特殊含义的符号都将被转义(<变得&lt;等)。

要将字符串呈现为纯 HTML 代码,请使用safe过滤器。

视图.py:

state = "<img src="some.jpg" /> Your username and/or password were incorrect."

索引.html:

<span class="state-txt">{{ state|safe }}</span>
于 2013-08-08T22:08:43.610 回答
0

不要渲染图像。否则试试

视图.py

if user is not None:
        if user.is_active:
            login(request, user)            
            state = True
            return render_to_response('uc/portal/index.html', {'state':state, 'username':username}, context_instance=RequestContext(request))
        else:
            state = False
    else:
        state = False

在模板中

{%if state %}  
   <img></img>
   you are successfully logged in.
{%endif%}
于 2013-08-08T20:59:23.027 回答