tuergeist
tuergeist

Reputation: 9401

How to replace placeholders in placeholders (variables) in Django?

In a Django template, I'd like to add text from a model field. This text field can be understood as text-template itself. It may look like:

Dear {{user}},
thank your for...
Regards,
  {{sender}}

This text field is available as emailtemplate inside a normal Django template. The fields from above (user=Joe, sender=Alice) are available as well.

{% extends 'base.html' %}
{% block content %}

{{ emailtemplate }}    

{% endblock %}

The output shall be as follows

Dear Joe,
thank your for...
Regards,
  Alice

I have no clue how to do this with built-in methods. My only idea is to parse emailtemplate manually before I hand it over to the template engine, thus inside the view. But I'm sure, I'm not the first one with that problem.

Upvotes: 3

Views: 1366

Answers (1)

Yannic Hamann
Yannic Hamann

Reputation: 5215

After several reworks, I came up with the following solution. Double check who can modify/alter the template string since this could be a big security flaw, if alterable by the wrong people.

views.py:

class YourView(TemplateView):    
    template_name = 'page.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["emailtemplate"] = "Dear {{user}}, {{sender}}"
        context["user"] = "Joe"
        context["sender"] = "Alice"
        return context

page.html:

{% extends 'base.html' %}
{% load core_tags %}

{% block content %}

{% foobar emailtemplate %}

{% endblock %}

your_app/templatetags/core_tags.py (don't forget the __init__.py file to ensure the directory is treated as a Python package your_app must also be in INSTALLED_APPS):

from django import template
from django.template import Template

register = template.Library()


@register.simple_tag(takes_context=True)
def foobar(context, ts):
    t = Template(template_string=ts)
    return t.render(context)

See also:

https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#code-layout https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#simple-tags

Upvotes: 3

Related Questions