John
John

Reputation: 95

Would it be a bad idea to use Django template tags to add context to a template? (Trying to imitate ease of Vue components)

One of the problems I have with Django (at least how I've learned to use it so far) is that there's not a great way to build components like in Vue.

In my templates I have been using {% include %} statements to include more modular pieces of template code/components. the problem, though, is that if I use a piece of data in the component then it needs to be passed to every single view that I use it in.

For example, suppose I have this template:

<p>I'm a template!</p>

{% include './components/weather.html' %}

and then in ./components/weather.html:

<p>The weather is {{ weather.status }} today.</p>

Now, in any view that I want to use weather.html in, I will need to pass in 'weather' as a context variable. It would be better if I could just include a template in another template and know that it will automatically make the database requests needed to populate the context it needs.

Is there any reason I can't use a tag for this? Like instead of {{ weather.status }} use {% weather %} and then in template tags something like:

@register.simple_tag
def weather():
    return weather.get_status()

Is this going to open up some vulnerability I don't see or is there a better more Django-ey way to do this?

Upvotes: 1

Views: 149

Answers (1)

phyominh
phyominh

Reputation: 306

I don't see anything preventing you from making a custom tag. That's what custom template tags are for - to provide functionality that is not covered by the built-in tags. The only vulnerability you need to look out is when you're rendering user-submitted data and you have to HTML escape the data.

Inclusion tags may be the closest thing to "components". You can add a template file to inclusion tags and from there add your desired data to the template. This way you might avoid adding context variable to every page you want to add your data to.

There's a third-party package called django-component which I found on PyPI. Using that package might give you the ability to write Vue-ish code but under the hood it's also using Django's template API which is used to create the custom tags and filters.

Upvotes: 2

Related Questions