I just have a question about how to achieve DRY with javascript that generates html on the fly. I have a list of elements that are loaded dynamically and populated by the django开发者_开发知识库 template a la
{{ tag.title }}
{% if request.user.is_authenticated %}
<a name="del-tag" data-id="{{ tag.id }}" class = "tag-x" title="Remove Tag" href="#">x</a>
{% endif %}
Now, I have some javascript that also loads new tags via ajax. Here's the relevant portion:
var newTag = "<span class = \"tag\">" + tagName + "<a name=\"del-tag\" data-id=\"" + tag_id + "\"" +
"class = \"tag-x\" title=\"Remove Tag\" href=\"#\">x</a></span>";
$('#tags').append(newTag);
Can I avoid duplicating HTML in the javascript?
Thanks.
jQuery Template could be used for this.
jquery(I'm assuming that's jquery that you are using) has a clone feature that can clone DOM elements. Given that you should be able to clone one of the html elements that already exist and change the value of the attributes, and then append it back to the DOM. I have not done this myself but it should work in theory.
Yes, you can do this. Have all tags generation functionality in a separate template. Then have some url which generates tags. Like this:
www.example.com/tags/?tags=tag1,tag2,tag3
this produces:
Then, when doing the AJAX call in your code do something like this:
$('div.tags').load('www.example.com/tags/?tags=tag1,tag2,tag3')
On the Django/template side you'd want to find a way how to include the result returned by the URL into the page template body. I'm not exactly sure what tools Django template engine provides, but on the first view it looks like you could put this code into some view method and extend this view everywhere you need it, providing the template variable as following render(..., tags=self.generate_tags(args))
, in template it would be just {{ tags }}
.
Both /tags/?tags=...
and regular page /page/
calls could re-use the generate_tags()
method then.
Hope it helps
精彩评论