aroooo
aroooo

Reputation: 5076

Relative Template Import

I have a template located in templates/mytemplate.html in my app and I need to reference the template file directly in code to turn it into a string to use with send_mail(). How can I do this? Here's what I've tried:

from django.template import loader

html_message = loader.render_to_string(
            'appname/templates/mytemplate.html',
            {
                'username': user.name,
            }
        )

Upvotes: 0

Views: 40

Answers (1)

nhuntwalker
nhuntwalker

Reputation: 66

If that's the way your templates are set up, you should just be able to reference it by name

loader.render_to_string('mytemplate.html', {
    'username': user.name,
})

However be aware that in case you have any name conflicts within your Django project (or even if you don't), it's better to have a directory that mirrors the app name within your templates directory. Your tree structure for an app would look like this:

appname/
    some_file.py
    templates/
        appname/
            mytemplate.html

Then you would just reference it as loader.render_to_string('appname/mytemplate.html', {...})

Upvotes: 1

Related Questions