webstack/webstack-django-sorting

Translations and variables fail when using Django cached template Loader

kimchi-jjigae opened this issue · 1 comments

Hi, thanks for the great library.

I'm encountering an issue when I use localisation in the anchor tags, but only when I used the cached template loader django.template.loaders.cached.Loader

The displayed titles are set to whichever language is set when the template is loaded for the very first time. Every user gets the titles in this language, no matter what their language setting is.

This is because the SortAnchorNode.__init__() function is only run once before cacheing, thus the self.title variable is cached too and set to the value of the first language chosen, and cannot be overwritten.

Also, variables can fail with the cached template loader too.
The first time render() is called, then it sets self.title to the resolved variable.
Then the next time the render() is called, the line self.title = context[self.title] results in a KeyError, as it tries to find the resolved variable in the context again (instead of the variable name)

My solution for these problems is to modify the library so that:

  • the Node __init__() takes an additional variable 'self.title_needs_translation'. Then I conduct the translation in render() instead of anchor(), (since that function is run every time the view is called).
  • use a variable display_title in render(), which reevaluates the title to be rendered instead of setting self.title again

If you have any better ways to solve this, then please let me know. I've also made a pull request with the changes that I've made.

PR merged, thank you.