Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile a template saved in database in django

I am building an email sending application, I have many HTML templates stored in the database, So for each recipient, I need to customize this template by merging the tags/placeholders in the HTML,

example email template

<html>
 ....
     Hello {{ Name }},
 ....
</html>

So I need to compile this based on the context variables I have. Like we compile Django templates, How can I do this in the current scenario,

Tried, render_to_string() and get_template() functions, but they look for the actual template files stored in the templates/ folder.

like image 912
Shobi Avatar asked Oct 30 '25 22:10

Shobi


1 Answers

There are two methods:

  1. Use from_string() : https://docs.djangoproject.com/en/2.1/ref/templates/api/#django.template.Engine.from_string

  2. Use Template object directly.

Example.

    from django.template import Template

    template = Template("My name is {{ my_name }}.")
like image 89
kawadhiya21 Avatar answered Nov 02 '25 13:11

kawadhiya21



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!