What is wrong with my Django templating use of if's?

让人想犯罪 __ 提交于 2019-12-12 03:01:15

问题


{% 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 }}">&amp;#10008;</span> &nbsp;
{% 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://'.

The templating engine is complaining that '{% if ":" not in url.url %}' is invalid syntax. What is the correct syntax / approach here?


回答1:


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/


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...




回答2:


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. 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 e.g. if you have designers creating html/css templates

edit: This also frees you up to perform more advanced logic in the full_url property (like checking for spam, broken links, etc)



来源:https://stackoverflow.com/questions/16005757/what-is-wrong-with-my-django-templating-use-of-ifs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!