/modules/mod_base/filters/filter_first.erl

https://code.google.com/p/zotonic/ · Erlang · 49 lines · 25 code · 8 blank · 16 comment · 0 complexity · 63423f2f012585260cfcb22b262861b3 MD5 · raw file

  1. %% @author Marc Worrell <marc@worrell.nl>
  2. %% @copyright 2010 Marc Worrell
  3. %% @doc 'first' filter, return the first element in a string or list
  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_first).
  18. -export([
  19. first/2,
  20. first/3
  21. ]).
  22. -include("zotonic.hrl").
  23. first(undefined, _Context) ->
  24. undefined;
  25. first(<<First, _/binary>>, _Context) ->
  26. First;
  27. first(Other, Context) ->
  28. case erlydtl_runtime:to_list(Other, Context) of
  29. [] -> <<>>;
  30. [H|_] -> H
  31. end.
  32. first(undefined, _Length, _Context) ->
  33. undefined;
  34. first(Value, Length, Context) ->
  35. first1(erlydtl_runtime:to_list(Value, Context), Length, []).
  36. first1([], _N, Acc) ->
  37. lists:reverse(Acc);
  38. first1(_L, 0, Acc) ->
  39. lists:reverse(Acc);
  40. first1([H|T], N, Acc) ->
  41. first1(T, N-1, [H|Acc]).