Hay, I'm writing some templates but I want to convert " " into "_" within a string.
嘿,我在写一些模板但是我想把" " "转换成"_"在一个字符串中。
I want to convert the output of
我想要转换输出
{{ user.name }}
from something like "My Name" to "My_Name". How do I do this?
从“我的名字”到“My_Name”。我该怎么做呢?
4 个解决方案
#1
10
There is no built-in tag or filter to do this replacement. Write a filter that splits by a given character, and then combine that with the join
filter, or write a filter that does the replacement directly.
没有内置的标签或过滤器来做这个替换。编写一个由给定字符分割的过滤器,然后将其与联接过滤器合并,或者编写一个直接进行替换的过滤器。
#2
73
A shorter version of Matthijs' answer:
Matthijs的简短回答:
{{ user.name.split|join:"_" }}
Of course it only works when splitting on whitespace.
当然,它只适用于分割空格。
#3
6
I like to perform this type of conversions in my view / controller code i.e.:
我喜欢在我的视图/控制器代码中执行这种类型的转换,例如:
user.underscored_name = user.name.replace(' ','_')
context['user'] = user
dont be afraid to just add a new (temporary) property and use this in your template:
不要害怕添加一个新的(临时的)属性并在模板中使用:
{{ user.underscored_name }}
If you use this at more places add the method underscored_name to the User model:
如果您在更多的地方使用此方法,请将underscored_name方法添加到用户模型中:
class User()
def underscored_name(self):
return self.name.replace(' ','_')
#4
4
If you dont like to write your own custom tag you could do it like this ...
如果你不喜欢写你自己的自定义标签,你可以这样做……
{% for word in user.name.split %}{{word}}{% if not forloop.last %}_{% endif %}{% endfor %}
However its quite verbose ...
然而,它相当冗长……
#1
10
There is no built-in tag or filter to do this replacement. Write a filter that splits by a given character, and then combine that with the join
filter, or write a filter that does the replacement directly.
没有内置的标签或过滤器来做这个替换。编写一个由给定字符分割的过滤器,然后将其与联接过滤器合并,或者编写一个直接进行替换的过滤器。
#2
73
A shorter version of Matthijs' answer:
Matthijs的简短回答:
{{ user.name.split|join:"_" }}
Of course it only works when splitting on whitespace.
当然,它只适用于分割空格。
#3
6
I like to perform this type of conversions in my view / controller code i.e.:
我喜欢在我的视图/控制器代码中执行这种类型的转换,例如:
user.underscored_name = user.name.replace(' ','_')
context['user'] = user
dont be afraid to just add a new (temporary) property and use this in your template:
不要害怕添加一个新的(临时的)属性并在模板中使用:
{{ user.underscored_name }}
If you use this at more places add the method underscored_name to the User model:
如果您在更多的地方使用此方法,请将underscored_name方法添加到用户模型中:
class User()
def underscored_name(self):
return self.name.replace(' ','_')
#4
4
If you dont like to write your own custom tag you could do it like this ...
如果你不喜欢写你自己的自定义标签,你可以这样做……
{% for word in user.name.split %}{{word}}{% if not forloop.last %}_{% endif %}{% endfor %}
However its quite verbose ...
然而,它相当冗长……