/modules/mod_base/filters/filter_truncate.erl

http://github.com/zotonic/zotonic · Erlang · 47 lines · 25 code · 6 blank · 16 comment · 0 complexity · 90f18a4b434c2211e027efbfbb844e95 MD5 · raw file

  1. %% @author Marc Worrell <marc@worrell.nl>
  2. %% @copyright 2010 Marc Worrell
  3. %% @doc 'truncate' filter, truncate a string on a certain length, taking word boundaries into account.
  4. %% Copyright 2010 Marc Worrell
  5. %%
  6. %% Licensed under the Apache License, Version 2.0 (the "License");
  7. %% you may not use this file except in compliance with the License.
  8. %% You may obtain a copy of the License at
  9. %%
  10. %% http://www.apache.org/licenses/LICENSE-2.0
  11. %%
  12. %% Unless required by applicable law or agreed to in writing, software
  13. %% distributed under the License is distributed on an "AS IS" BASIS,
  14. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. %% See the License for the specific language governing permissions and
  16. %% limitations under the License.
  17. -module(filter_truncate).
  18. -export([truncate/2, truncate/3, truncate/4]).
  19. truncate(In, Context) ->
  20. truncate(In, 20, Context).
  21. truncate(In, N, Context) ->
  22. truncate(In, N, <<226,128,166>>, Context).
  23. truncate(undefined, _N, _Append, _Context) ->
  24. undefined;
  25. truncate(S, N, Append, Context) when not is_integer(N) ->
  26. truncate(S, z_convert:to_integer(N), Append, Context);
  27. truncate({trans, _} = Tr, N, Append, Context) ->
  28. truncate(z_trans:lookup_fallback(Tr, Context), N, Append, Context);
  29. truncate(In, N, Append, _Context) when is_binary(In) ->
  30. z_string:truncate(In, N, z_convert:to_binary(Append));
  31. truncate(In, N, Append, _Context) when is_list(In) ->
  32. z_string:truncate(iolist_to_binary(In), N, z_convert:to_binary(Append));
  33. truncate(In, N, Append, Context) ->
  34. case z_template_compiler_runtime:to_simple_value(In, Context) of
  35. L when is_list(L) ->
  36. truncate(L, N, Append, Context);
  37. B when is_binary(B) ->
  38. truncate(B, N, Append, Context);
  39. _ ->
  40. undefined
  41. end.