How can I implement string substitution in django's default templating engine? I'm trying to basically implement "hello %s" % "world" with stringformat. I can't seem to get it right. My best attempt so far {{ "hello %s"|stringformat:"world" }} gets me no output.
1 Answer
In stringformat:E , the E signifies the conversion types which is Floating Point Exponential Format in this case. Here, "world" is not a valid conversion type, hence it fails.
This cannot be done, as the parameter into a templatetag method has to be a context variable. The idea of stringformat is to convert types, and not format strings the way you are looking to do.
5 Comments
Steven Wexler
I'm confused because Otherwise, values must be a tuple with exactly the number of items specified by the format string suggests that I can use
stringformat to substitute values into my string. This is why "hello %s" % "world" or "hello %s" % ("world") works as I expect.Daniel Roseman
@steaks why would you think that? The docs, as karthikr quoted, talk about formatting, not substitution. There is no reference to string substitution in the docs, and
stringformat doesn't do it.Steven Wexler
@daniel I think that because for a few reasons. One, the docs specify items specified by the format string which I interpret as the %s or similar characters in the string argument. Second, my hello world example works. Third, the docs give a "substitution" example. See the python has 002 quotes example. Right now I'm thinking that the string fomatting operator does support what I want. However, the stringformat tag doesn't support all of the features of the string formatting operator.
karthikr
There is only this much a template can do. Yes, your string formatting would work the way intended in the view, for example - but not in the django templates. If you really want that functionality, you can always write a templatetag to achieve the same
Steven Wexler
@daniel Between your and karthikr's comments I understand why stringformatter doesn't work the way I want. I'll create a custom template tag. Thanks to both of you. You were very helpful!