ブログ記事の一覧などで、本文をすべて表示するには長すぎる。文頭だけ表示したい、という場合があると思う。
こんなとき、テンプレートの3項演算子を使うとすっきり書ける。
${str.length() > 20 ? str[0..19]+'...' : str }
20文字を超えるときは20文字まで表示して「…」と続きがあることを匂わす。
20文字以内の場合はそのまま表示する。
記述が面倒なので、カスタムテンプレートタグ化してしまっても良いかも。
#{set '_doBody'}#{doBody/}#{/set}
%{
if (!_str) {
_str = _doBody;
}
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}
%{
}
}%
使い方
パラメータは3つ。
strは対象となる文字列、lengthを超えるとき省略が行われる。
contは省略時に末尾に付ける文字列。指定しないときは、’…’となる。
対象の文字列をタグで挟む記法にも対応しています。
%{
def txt='現在表示しているページに該当するメニューのa要素に「class="active"」を指定すると、メニューボタンの色が変わり、ナビゲーションの役割を果たします。'
}%
#{shorten str:txt, length:20, cont:'...' /}<br/>
#{shorten length:20, cont:'...' }${text}#{/shorten}<br/>