I won't be offended if you just send a link to where this has already been answered. I haven't found an answer to this.
I'm working on a site where a cached template loader is enabled. They have a custom template tag that they call on many pages, and one of the values passed to this tag is the unique article ID of the page that called it. The problem is that the cached template loader seems to be caching the values too, so even though each page is passing its article ID to the tag, the tag is using the cached article ID.
Is there a way to disable the cached template loader for a single template tag?
Here is some code if it's helpful:
This is the cached template loader setting:
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
When I comment out this setting and restart the server, the issue goes away, so I know it has "something" to do with caching.
That doc linked above also talks about making sure template tags are thread-safe. Is this because of how the template gets stored in the cache? What I take from that note about thread-safety is that values passed to template tags shouldn't be assigned to the node itself, but to the render_context. Am I on the right track?
Here is a sample of what my code is doing:
Calling the tag on page 1:
{% my_tag article_id="{{object.article_id}}" %}
Calling the tag on page 2:
{% my_tag article_id="{{object.article_id}}" %}
In both of the above cases, object.article_id is a template variable that contains the article ID for the page calling the template tag.
Below is the template tag code (simplified).
@register.tag(name="my_tag")
def do_my_tag(parser, token):
article_id = None
values = token.split_contents()
kwargs = get_kwargs(values[1:])
if "article_id" in kwargs:
article_id = kwargs["id"]
return DoMyTagNode(article_id)
class DoMyTagNode(template.Node):
def __init__(self, article_id):
self.article_id = article_id
self.template = get_template('path/to/template.html')
def render(self, context):
article_id = Template(self.article_id).render(context)
context.update({ 'article_id': article_id })
return render_to_string(self.template, context)
Any help would be greatly appreciated!