Skip to content Skip to sidebar Skip to footer

What Is Wrong With My Django Templating Use Of If's?

{% for url in urls %}

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

Solution 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:

classUrl(models.model):
    url = model.TextField()

    @propertydeffull_url(self):
        if":"notin 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)

Post a Comment for "What Is Wrong With My Django Templating Use Of If's?"