playframework1‎ > ‎template‎ > ‎

長い文字列を省略する

Url Redirector Modified

ブログ記事の一覧などで、本文をすべて表示するには長すぎる。文頭だけ表示したい、という場合があると思う。
こんなとき、テンプレートの3項演算子を使うとすっきり書ける。
 

${str.length() > 20 ? str[0..19]+'...' ? str }

 
20文字を超えるときは20文字まで表示して「...」と続きがあることを匂わす。
20文字以内の場合はそのまま表示する。


記述が面倒なので、カスタムテンプレートタグ化してしまっても良いかも。
app/views/tags/shorten.html
%{
    if (!_str) {
        _str = '';
    }
    if (!_length || _length == 0) {
        throw new play.exceptions.TagInternalException("length attribute cannot be empty for shorten tag");
    }
}%
%{
    if (_str.length() > _length) {
}%
${_str[0.._length]}${_cont ? _cont : '...'}
%{
    } else {
}%
${_str}
%{
    }
}%

使い方
#{shorten str:url, length:100, cont:'<続きは省略しました>' /}
パラメータは3つ。
strは対象となる文字列、lengthを超えるとき省略が行われる。
contは省略時に末尾に付ける文字列。指定しないときは、'...'となる。