开发者

Django templates split text on fullstop

Using django templates I would like to split a block of text on the first fullstop. I would then like to give the first sentence a class of highlight and then the rest of the text a class of normal. how would i do this? e.g. (I know this doesn't work)

text = Aliquam pretium vestibulum nibh, vel molestie velit varius nec Curabitur non neque sed elit tincidunt. Dignissim eget vel du molestie magna auctor faucibus. Curabitur id nisl nec ipsum molestie egestas in at dolor. Morbi et risus ac quam sagittis accumsan. Morbi vitae elementum metus. Vestibulum malesuada ornare elit, et interdum nisi imperdiet sed.

<p class="highlight">{{text|split:"."[0]}}</p>
<p clas开发者_如何学Pythons="normal">{{text|split:"."[1]}}</p>

which would give

<p class="highlight">Aliquam pretium vestibulum nibh, vel molestie velit varius nec Curabitur non neque sed elit tincidunt.</p>

<p class="normal">Dignissim eget vel du molestie magna auctor faucibus. Curabitur id nisl nec ipsum molestie egestas in at dolor. Morbi et risus ac quam sagittis accumsan. Morbi vitae elementum metus. Vestibulum malesuada ornare elit, et interdum nisi imperdiet sed.</p>

I am using Django 1.1


Define a custom filter, say mysplit.

@register.filter
def mysplit(value, sep = "."):
    parts = value.split(sep)
    return (parts[0], sep.join(parts[1:]))

Then use the filter in your template:

{% with text|mysplit:"." as parts %}
    <p class="highlight">{{ parts.0 }}</p>
    <p class="normal">{{ parts.1 }}</p>
{% endwith %}

This was tested with Django 1.2.1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜