2013-07-17 35 views
2

我想转换字符串在Django模板列表:如何转换字符串中的Django模板列出

数据:

{u'productTitle': u'Gatsby Hard Hair Gel 150g', u'productPrice': 0.0, u'productMRP': 75.0, u'hasVariants': 0, u'productSite': u'http://www.365gorgeous.in/', u'productCategory': u'', u'currency': u'INR', u'productURL': u'http://www.365gorgeous.in/gatsby-hard-hair-gel-300g-1.html', u'productDesc': u'A Water type hair gel with is hard setting and gives hair a firm hold It is non sticky hard setting and smooth to the touch Firm hold with wet look spikes', u'productSubCategory': u'', u'availability': 0, u'image_paths': u'["full/548bc0f93037bd03340e11e8b18de33b414efbca.jpg"]'} 

我想从上面的字典中提取图像路径,但图像路径在串u'["full/548bc0f93037bd03340e11e8b18de33b414efbca.jpg"]'是有什么办法可以把它转换成["full/548bc0f93037bd03340e11e8b18de33b414efbca.jpg"]内模板...我知道它可以在视图中进行,但我可以做这个模板....

+4

请问为什么这是一个字符串呢? – rantanplan

+3

......以及为什么你不想将逻辑放在你的视图中它属于哪里? – arie

+0

我同意这种事情不应该由模板处理。如果你将它存储为json,当你访问该字段时,会有很多包将自动处理序列化和反序列化。下面是一个例子:https://github.com/bradjasper/django-jsonfield – Ngenator

回答

3

你可以write a template filter运行字符串通过json dec颂。

{% for image_path in data.image_paths|your_custom_json_decode_filter %} 
    {{ image_path }} 
{% endfor %} 

虽然这不是一个好主意,但为什么不在你的视图中这样做呢?

+3

我认为这不是一个好的方式,因为在将来他可能会有另一个源码不会格式化他的字典和image_paths。他最好不得不通过使用一个对象来抽象它,或者在他看来做这个工作。 但您的答案将按预期工作。 – gpichot

+2

哦,我的上帝为什么?他可以编写一个编译器作为模板过滤器 - 他应该这样做吗?这里的工作明显有缺陷。 – rantanplan

+1

很明显,在这里使用某种API,如果有一天他想支持另一个API呢?他将不得不重写模板和视图。如果他想保留一个长期的MVC项目,那么在模板中使用这种逻辑不是一个好方法。 – gpichot

0

模板过滤器是您的最佳选择,因为没有内置模板标签来评估字符串。如果你想在模板中转换它,那是你最好的选择。但是,如果在将数据发送到模板之前修改数据,那么在python中构建模板过滤器就没有多大意义。无论哪种方式,你将不得不在python中做些什么。 如果你打算使用此模板过滤器是一个例子:

@register.filter # register the template filter with django 
def get_string_as_list(value): # Only one argument. 
    """Evaluate a string if it contains []""" 
    if '[' and ']' in value: 
     return eval(value) 

,然后在模板中,您将要循环的关键,在你的字典中的值和值传递给您的自定义模板过滤器等等:

{% for image_path in data.image_paths|get_string_as_list %} 
    {{ image_path }} 
{% endfor %} 
+0

这太不安全了...... [Eval真的很危险](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – Ngenator

+0

如果你有** untrusted **输入,'eval'只会是危险的。他的数据显然来自数据库,并且是服务器端的图像路径。他应该是安全的,如果没有,他的过滤器可以检查有效性。 –

+0

@ notbad.jpeg假定输入数据库的数据是有效的。当解码json是一个选项时,应该不需要使用eval所涉及的风险。 – Ngenator

相关问题