我正在使用字符串 .format()
函数使用关键字参数格式化我的字符串。我将一些基本对象传递给字符串,并在字符串中使用这些对象的属性。例如:
"Hello, {user.first_name}!".format(user=my_user)
这些字符串可能会在 HTML 电子邮件中使用,因此替换字段应该是 HTML 转义的(使用 django.utils.html.escape)。
格式化字符串时,对字符串替换字段使用转义函数的最佳方法是什么?如果这不可能,那么字符串格式化的适当替代方案是什么?我的字符串存储在数据库中并通过 Django 管理界面进行修改。
I am using the string .format()
function to format my strings with keyword arguments. I pass in some basic objects to the strings and use attributes of these objects in the strings. For example:
"Hello, {user.first_name}!".format(user=my_user)
These strings may be used in HTML e-mails, so the replacement fields should be HTML-escaped (using django.utils.html.escape
).
What is the best way to use an escape function for string replacement fields when formatting a string? If this is not reasonably possible, what is an appropriate alternative to string formatting? My strings are being stored in a database and modified through the Django admin interface.
发布评论
评论(2)
好吧,问题是你为什么要使用格式。您不打算将其推入模板吗?我的意思是,如果您转义模板中的某些内容(使用模板标签),您几乎只是通过此转义函数传递一个字符串。
也许这不是您正在寻找的,但您不想这样做吗
?
如果你想逃避所有的争论并且你确信它们会
字符串,
你也可以做一些更疯狂的事情,比如,
如果你想让东西变得疯狂!
Well, the question is why you are using format to begin with. Aren't you going to push this to a template? I mean, if you escape something in your template (using a template tag) you're pretty much just passing a string through this escape function.
Maybe this isn't what you're looking for but would't you just do,
?
If you wanted to escape all your arguments and you were sure they would be
strings,
You could also probably do something a little more crazy like,
if you wanted stuff to get CRAZY!
作为使用 Django 模板之前的临时解决方案,我将
string.Formatter
进行了子类化,如 文档。该解决方案也应该在 Django 之外工作(但显然需要替换
escape
函数)。As a temporary solution before I move to using Django templates, I subclassed
string.Formatter
as mentioned in the documentation.This solution should work outside of Django as well (the
escape
function will obviously need to be replaced though).