刷新< div>由django模板生成的元素 [英] Refresh <div> element generated by a django template

查看:178
本文介绍了刷新< div>由django模板生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何刷新django模板中的某个元素?

示例:

How do I refresh a certain element within a django template?
Example:

{% if object.some_m2m_field.all %}
    <h3>The stuff I want to refresh is below</h3>
    <div id="the-div-that-should-be-refreshed">
    {% for other_object in object.some_m2m_field.all %}
        <a href="www.example.com">{{ other_object.title }}</a>
        &nbsp;
    {% endfor %}
    </div>
{% endif %}

让我们说一些页面中的其他元素触发一个javascript应该刷新上面的div。有没有办法使django刷新模板中的这个特定元素?

Lets say some other element in the page triggers a javascript that should refresh the div above. Is there a way to cause django to refresh this specific element within the template?

如果没有,我将不得不使用常规的JS或jQuery方法来修补div而不是使用django的模板层的巨大力量。另外,上面的代码是一个简化的实际模板,我使用很多模板的力量,所以猴子修补所产生的html将是一场噩梦...

If not, I'll have to monkey-patch the div using regular JS or jQuery methods and not use the great power of django's template layer. Also, the above code is a simplification of the actual template, I use much of the template's power, so monkey-patching the resulting html will be a nightmare...

推荐答案

您可以使用异步请求填充div元素。
异步请求由django使用模板引擎回答。

You could use an async request to fill the div element. The async request is answered by django using the template engine.

在这种情况下,您将不得不将div元素的模板代码外包到单独的模板中文件。

In this case you would have to outsource the template code of the div element into a seperate template file.

更新示例:

strong>

要异步刷新视图,请使用JQuery,例如:

Javascript:
For refreshing the view asynchronously, use JQuery for example:

$.ajax({
  url: '{% url myview %}',
  success: function(data) {
  $('#the-div-that-should-be-refreshed').html(data);
  }
});

异步查看

def myview(request):
    object = ...
    return render_to_response('my_template.html', { 'object': object })

模板:

{% for other_object in object.some_m2m_field.all %}
    <a href="www.example.com">{{ other_object.title }}</a>
    &nbsp;
{% endfor %}

祝贺!

这篇关于刷新&lt; div&gt;由django模板生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆