Opened 3 years ago

Last modified 3 years ago

#28618 assigned New feature

Add an easier to make templates substitutions raise an exception on error

Reported by: Facundo Batista Owned by: shreyas
Component: Template system Version: 1.11
Severity: Normal Keywords: template error substitution
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


My idea is to have a way (maybe a config flag, default to False) to make templates subsystem to raise an error in the case of a substitution problem (and not ignore silently or fill with a default value).

My goal here is to enable this flag *when running my project tests*, not in production.


Change History (6)

comment:1 Changed 3 years ago by shreyas

Owner: changed from nobody to shreyas
Status: newassigned

comment:2 Changed 3 years ago by shreyas

It seems that there is a way to pass parameter string_if_invalid when initializing template engine which will be rendered in template if variable is not resolved from context. You can also pass %s in that string which will be interpolated with missing variable name.

For Eg.

engine = Engine(debug=True, string_if_invalid="Variable not found %s")
t = engine.from_string("{{articlecovfefe.section}}")
c = Context({"article": {"section": "News"}})
print(t.render(c))  # prints 'Variable not found articlecovfefe.section' != 'News'

Is it possible to leverage this in test cases for you.

comment:3 Changed 3 years ago by Facundo Batista

Yes, a string can be fixed so if a substitution fails, that can be searched in the test.

But that would imply to remember on EVERY test to check if that string exists (or change your testing infrastructure to assert that on all tests...).

In the spirit of "Errors should never pass silently" I think it would be useful to have a parameter like Engine(..., exception_on_missing_substitution=True) with default to False, so any missing substitution would explicitly make the test fail, without the developer needing to remember anything...

comment:4 Changed 3 years ago by shreyas

Good point.

Let's discuss this in Django dev mailing list and get other people's opinion.

comment:6 Changed 3 years ago by Tim Graham

Summary: There should be a way to make Templates substitution to raise an exception on errorAdd an easier to make templates substitutions raise an exception on error
Triage Stage: UnreviewedAccepted

As noted on the mailing list, this is already possible by setting TEMPLATES ['OPTIONS']['string_if_invalid'] to a class with a __str__() that raises an exception. A proposal from the mailing list thread is to add a new 'if_invalid' option that's a callable which would allow more advanced behavior (raise an exception, logging, etc.). Tentatively accepting that approach. See #24199 for some related information about the problem.

Note: See TracTickets for help on using tickets.
Back to Top