Christos Hayward
Christos Hayward

Reputation: 5993

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 }}">&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?

Upvotes: 0

Views: 77

Answers (2)

perrygeo
perrygeo

Reputation: 385

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)

Upvotes: 0

Fran&#231;ois Constant
Fran&#231;ois Constant

Reputation: 5496

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

Upvotes: 1

Related Questions