PageRenderTime 27ms CodeModel.GetById 17ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

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