'Django render_to_string not including certain context variables when rendering

I have searched here and not found anything so far that helps.

When using render_to_string and providing context variables, one of these variables gets used by the template as expected, however, another variable seems completely ignored.

The view. Creates a chunk of HTML consisting of the rendered thumbnail templates. NB: the 'image' context works fine! It is only the 'click_action' that seems to be ignored.

def ajax_build_image_thumbnail(request):
    image_ids = request.POST.get('ids', None)
    html_string = ''
    response = {}
    for id in image_ids:
        image_instance = UserImage.objects.get(pk=id)
        context = {
            'click_action': "showEditImageModal",
            'image': image_instance,
        }
        html_string += render_to_string('auctions/includes/imageThumbnail.html', context)
    response['html'] = html_string
    return JsonResponse(response)

The imageThumbnail template:

<div id="{{ image.id }}">
    <a href="#" data-click-action="{{ click_action }}"></a>
</div>

The result:

<div id="265">
    <a href="#" data-click-action=""></a>
</div>

The expected result:

<div id="265">
    <a href="#" data-click-action="showEditImageModal"></a>
</div>

So, as you can see, the data-click-action attribute on the anchor is blank in the rendered template, where it should contain the context variable "click_action"

Things I have tried:

  • Using autoescape
  • Wrapping the anchor in a {% with %} tag and setting "click_action" as a local template variable.
  • Hard-coding "click_action" in the view, and setting it to a variable.
  • Switching the order of variables (thinking in case the function only renders the first context variable for some reason).
  • Every combination of single and double quotes.

Any ideas? I feel like I am missing something stupidly obvious. Cheers!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source