I have a function in my Django app that has a dictionary containing several long strings. When that function is called, those strings are formatted and the dictionary returned.
For example:
def my_strings(foo, bar, baz):
return = {
'string1': 'a really long string! %s' % foo,
'string2': 'another long one. %s %s' % (foo, bar),
'string3': 'yet another! %s %s %s' % (foo, bar, baz),
}
However, having all these long strings, stored in a Python file is ugly and it seems there should be a cleaner way to do it.
I’d toyed with putting them in a template file and doing some rendering, like so:
mytemplate.txt
{% if string1 %}
a really long string! {{ foo }}
{% endif %}
{% if string2 %}
another long one. {{ foo }} {{ bar }}
{% endif %}
{% if string3 %}
yet another! {{ foo }} {{ bar }} {{ baz }}
{% endif %}
Python
def my_strings(foo, bar, baz):
arg_dict = {
'foo': foo,
'bar': bar,
'baz': baz,
}
my_strings = {}
string_names = ['string1', 'string2', 'string3']
for s in string_names:
arg_dict[s] = True
my_strings[s] = render_to_string('mytemplate.txt', arg_dict).strip()
del arg_dict[s]
return my_strings
But that seems a little too roundabout, and most likely less performant.
Is there a preferred way in Python, or Django specifically, to handle storing and formatting long string assets?
Some extra context: the string assets are either HTML or plaintext. The dictionary is eventually iterated over and all instances of each key in yet another string are replaced with its string value.
I would treat this as something similar to the way many i8n compilation code does it.
Store the long strings in a dictionary in a separate file. Import that dictionary and then format the desired string in your code.