I have the following HTML template in a Python variable:
template = """
<script>
function work()
{
alert('bla');
}
</script>
Success rate is {value:.2%} percent.
"""
I want to substitute {value:.2%}
with some decimal number with the appropriate formatting. Since my template may contain a lot of JavaScript code, I want to avoid escaping the curly braces with {{
and }}
, so using template.format(...)
directly is not an option.
Using Template(template).substitute(...)
also seems impossible because I want advanced formatting for value
.
I could probably replace {value:.2%}
with a corresponding %(value)...
syntax and then use template % ...
. But I'm not a fan of this syntax because most of the variables in a real-world template won't need advanced formatting, so I want to keep the placeholder syntax simple.
So my question is, is it possible to use custom placeholders in the template that would allow for advanced formatting when necessary, i.e. to have simply {{value}}
or [[value]]
but also {{value:.2%}}
or [[value:.2%]]
?
Edit: Finally, I want to avoid errors that .format(...)
would produce when the template contains placeholders, such as {{dont_want_this_substituted}}
, for which the passed dictionary doesn't contain a value. That is, I want to only substitute only certain placeholders, not all that appear in the template.
Edit 2: To achieve what I want, I can grab all placeholders with a regular expression first, then format their contents and finally make the replacement in the template. But I wonder if an easier solution exists.
Edit 3: It was suggested that I split the template to avoid issues with format()
. I would like to avoid this, however, because the template actually comes from a file.