2011-01-16 4 views
1

django templatetagを探していて、単語を数え、単語を切り捨てずに段落全体を部分文字列にします。組み込み関数はありますか?私はDjangoのテンプレートドキュメントの組み込み関数リストを調べてみましたが、何も見つかりませんでした。django templatetag

助けてください?

答えて

1

これは私の実装です。それは実際に段落ではなく文章をチョップしますが、とにかく考えを得るべきです。

{% splitarticle some_data word_count %} 
    {{ pre_part }} 
    {% if post_part %} 
     {{ post_part }} 
    {% endif %} 

そして、それは二つの変数

そしてコードを返します。 <に入れてくださいyour_app>/templatetags/

from django import template 
from django.utils.encoding import force_unicode 

def split_by_sentence(text, word_count): 
    words = force_unicode(text).strip().split(' ') 
    word_count = int(word_count) 
    if len(words)>word_count: 
     cnt = word_count 
     for word in words[word_count:]: 
      cnt+=1 
      if '.' in word or '?' in word or '!' in word: 
       break 
     if cnt>=len(words): 
      cnt = word_count 

     pre = ' '.join(words[:cnt]) 
     post = ' '.join(words[cnt:]) 
     return pre, post  
    else: 
     return text, None 

register = template.Library() 
@register.tag 
def splitarticle(parser, token): 
    try: 
     tag, data, word_count = token.split_contents() 
    except ValueError: 
     raise template.TemplateSyntaxError('splitarticle parsing error') 
    return SplitArticleNode(data, word_count) 

class SplitArticleNode(template.Node): 
    def __init__(self, data, word_count): 
     self.data = template.Variable(data) 
     self.word_count = word_count 
    def render(self, context): 
     data = self.data.resolve(context) 
     context['pre_part'], context['post_part'] = split_by_sentence(data, self.word_count) 
     return '' 
1

私が知る限り、これを行うための組み込みタグはありません。あなたが望む言葉の性質(彼らは内部にないか、for-loopの一部です - これでも再帰的に行うことはできますが)は、あなたが望むことをviews.pyで行い、出力を渡すことができますテンプレートへの変数として?

ビューで部分文字列と語数を行い、テンプレートに対する回答を変数/リストとして渡しますか?

0

あなたはフィルタが必要だと思います。これまでのところ、スライスフィルタ https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#slice のdjangoテンプレートドキュメントを確認してください。また、trucatecharsとtrucatewordsフィルタもチェックしてください。 https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatechars,https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatewordsもう1つはhttps://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatewords-htmlで、これはhtmlでokです。これらのフィルタはすべて、djangoの開発版では不幸です。

関連する問題