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

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

问题描述

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

{% if object.some_m2m_field.all %}<h3>我要刷新的东西在下面</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;{% 结束为 %}

{% 万一 %}

假设页面中的其他一些元素触发了一个 javascript,它应该刷新上面的 div.有没有办法让 django 在模板中刷新这个特定的元素?

如果没有,我将不得不使用常规 JS 或 jQuery 方法对 div 进行猴子修补,而不是使用 django 模板层的强大功能.另外,上面的代码是对实际模板的简化,我使用了模板的大部分功能,所以猴子修补生成的 html 将是一场噩梦......

解决方案

您可以使用异步请求来填充 div 元素.Django 使用模板引擎响应异步请求.

在这种情况下,您必须将 div 元素的模板代码外包到一个单独的模板文件中.

更新示例:

Javascript:
对于异步刷新视图,例如使用 JQuery:

$.ajax({url: '{% url myview %}',成功:功能(数据){$('#the-div-that-should-be-refreshed').html(data);}});

异步视图:

def myview(request):对象 = ...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;{% 结束为 %}

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 %}

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?

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...

解决方案

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

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

UPDATED WITH EXAMPLE:

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);
  }
});

Async View:

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

Template:

{% 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天全站免登陆