[英]What is wrong with my Django templating use of if's?
{% for url in urls %}
<a id="URL_url_{{ url.id }}" class="edit_rightclick"
title="RIGHT click to edit."
href="{% if ":" not in url.url %}http://{% endif %}{{ url.url }}">{{ url.url }}</a>
<span class="delete" id="URL_{{ url.id }}">&#10008;</span>
{% endfor %}
The heuristic is intended to prepend the value of a partial or complete URL like google.com, under the assumption that sometimes people will paste a full browser URL, and sometimes people will type out google.com and never type 'http://'. 启发式方法的目的是假设部分网址或完整网址(例如google.com)的值放在前面,前提是人们有时会粘贴完整的浏览器URL,有时人们会键入google.com而从不键入“ http://” 。
The templating engine is complaining that '{% if ":" not in url.url %}' is invalid syntax. 模板引擎抱怨'{%if“:”不在url.url%}中'语法无效。 What is the correct syntax / approach here?
什么是正确的语法/方法?
What about using a filter for this: 如何为此使用过滤器:
href="{{ ulr.url|urlize }}"
Remember to check here before to build your own (look for urlize): https://docs.djangoproject.com/en/dev/ref/templates/builtins/ 切记在构建自己的文件之前检查此处(查找urlize): https ://docs.djangoproject.com/en/dev/ref/templates/builtins/
I think a better approach would be to the save the URLs as absolute ones within the admin and strip " http:// " when showing the link... 我认为更好的方法是将网址另存为admin中的绝对网址,并在显示链接时删除“ http:// ”。
As an alternative to using inline template statements or template filters, you could create a method/property on the model to handle the url creation logic. 作为使用内联模板语句或模板过滤器的替代方法,您可以在模型上创建方法/属性以处理url创建逻辑。 Assuming your Url is a model:
假设您的网址是一个模型:
class Url(models.model):
url = model.TextField()
@property
def full_url(self):
if ":" not in url.url:
....
return full_url
And use directly in the templates 并直接在模板中使用
href="{{ url.full_url }}">{{ url.url }}</a>
The templates stay clean and free of "business logic" which can be a good approach eg if you have designers creating html/css templates 模板保持整洁,没有“业务逻辑”,这是一个很好的方法,例如,如果您有设计师创建html / css模板,
edit: This also frees you up to perform more advanced logic in the full_url property (like checking for spam, broken links, etc) 编辑:这也使您有空在full_url属性中执行更高级的逻辑(例如检查垃圾邮件,断开的链接等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.