JavaScript / Django 设计模式
我只是有一个关于如何使用即时生成 html 的 javascript 实现 DRY 的问题。我有一个动态加载的元素列表,并由 django 模板填充。 现在
{{ 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 %}
,我有一些 javascript,它们也通过 ajax 加载新标签。这是相关部分:
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避免在javascript中重复HTML吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jQuery 模板 可以用于此目的。
jQuery Template could be used for this.
jquery(我假设您正在使用的是 jquery)有一个 clone 功能,可以克隆 DOM 元素。鉴于您应该能够克隆已存在的 html 元素之一并更改属性的值,然后将其附加回 DOM。我自己没有这样做过,但理论上应该可行。
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.
是的,你可以这样做。将所有标签生成功能放在单独的模板中。然后有一些生成标签的网址。像这样:
这会产生:
然后,当在代码中执行 AJAX 调用时,执行如下操作:
在 Django/模板端,您需要找到一种方法,将 URL 返回的结果包含到页面模板主体中。我不太确定 Django 模板引擎提供了哪些工具,但在第一个视图中,您似乎可以将此代码放入某个视图方法中,并在需要的任何地方扩展此视图,提供模板变量,如下所示
render( ...,tags=self.generate_tags(args))
,在模板中它只是{{ tags }}
。/tags/?tags=...
和常规页面/page/
调用都可以重用generate_tags()
方法。希望有帮助
Yes, you can do this. Have all tags generation functionality in a separate template. Then have some url which generates tags. Like this:
this produces:
Then, when doing the AJAX call in your code do something like this:
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 thegenerate_tags()
method then.Hope it helps