ブログ記事の一覧などで、本文をすべて表示するには長すぎる。文頭だけ表示したい、という場合があると思う。
こんなとき、テンプレートの3項演算子を使うとすっきり書ける。
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:'<続きは省略しました>' /} |
playframework1 > template >