0

スペース、タブ、改行、!、@、#、$、%、&、(、)、.、をダッシュ​​に置き換えるカスタム テンプレート タグがあります。

re.sub('[,@#$%&_.?!\t\n ]+', '-', value)

私が与えるとき、これはうまくいきますvalue parameter explicitly

re.sub('[,@#$%&_.?!\t\n ]+', '-', 'نمونه کد')

また:

value='نمونه کد'
re.sub('[,@#$%&_.?!\t\n ]+', '-', value)

しかし、テンプレートでは、オブジェクトのリストのフィールドでこのタグを使用したい場合、subject正しく機能せず、スペースをダッシュ​​に置き換えるだけです:

{% for n in news %}
   <a href="{% url CompanyHub.views.getNews n.subject|custom_unicode_slugify,n.pk %}" >{{n.description|safe|truncatewords_html:15}}</a>
{% endfor %}

これは私のカスタム テンプレート タグです。

def custom_unicode_slugify(value):
    return re.sub('[,@#$%&_.?!\t\n ]+', '-', value)

register.filter('custom_unicode_slugify', custom_unicode_slugify)

モデルメソッドが を返すため、n|custom_unicode_slugifyの代わりにこのタグを使用しようとしましたが、次のエラーが発生します。n.subject|custom_unicode_slugify__unicode__()subject field

Caught TypeError while rendering: expected string or buffer
4

1 に答える 1

0

私はついにこの解決策を思いつきました:テンプレートタグを使用unicode methodするとすぐには実行されないので、私はunicode subject__unicode__に次のことを見つけましたmodels.py

def __unicode__(self):
    return self.subject
def unicode_subject(self):
    return unicode(self.subject)

テンプレート内:

<a href="{% url CompanyHub.views.DocDetails doc.unicode_subject|custom_unicode_slugify,doc.pk %}">{{doc.content}}</a>
于 2012-07-14T13:10:28.257 に答える