简体   繁体   中英

CSS elements on django template with ajax

Using Django template as below to render a diction with CSS style:

<div id="div_unkown_txt">
{% for k, v in unkown.items %}
    <div>
    <span class='personal_word'>{{k}}</span> : {{v.2}}
    </div>
    <div class='dt'>{{v.1}}</div>
    <div>{{v.0|safe}}</div> 
{% endfor %}
</div>

Also i need to update div with ajax callback, so i write similar function unkown_html():

function unkown_html(k, v){
    return "<div><span class='personal_word'>" + k + "</span> : " + v[2] + "</div>" +
           "<div class='dt'>" + v[1] + "</div>" +
           "<div>" + v[0] + "</div>";
}
function repeat_word(w){
    $.ajax({
        type: "POST",
        url: '../word_repeat',
        data:{w:w}, 
        success: function(data){
            var txt='';
            $.each(data, function(k, v){ 
                txt += unkown_html(k,v);
            });
            $("#div_unkown_txt").html(txt);
        }
    });
}

the two functions are same, and since ajax is better for hot-plug rendering i want to know how to invoking unkown_html() in the template rendering?

Your question is a little hard to understand, unfortunately. I think you are asking about how to reduce the duplication between template code and Javascript when re-rendering part of a page in response to an Ajax call.

The way I usually deal with this is to get the Ajax call itself to return rendered HTML, rather than JSON. So you extract that template fragment into its own file, which you {% include %} into the normal template but call directly from the Ajax view. Then the Javascript simply has to insert the received HTML into the page, rather than re-rendering anything from scratch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM