Skip to content
Browse files

Make "linebreaks" more Erlang-y

  • Loading branch information...
1 parent ab53409 commit f40805af938d04c27a9b217268a9e73796f99939 @evanmiller evanmiller committed Mar 20, 2011
Showing with 25 additions and 9 deletions.
  1. +19 −9 src/erlydtl_filters.erl
  2. +6 −0 tests/src/erlydtl_unittests.erl
View
28 src/erlydtl_filters.erl
@@ -362,16 +362,26 @@ length_is(Input, Number) when is_list(Input), is_list(Number) ->
%% @doc Replaces line breaks in plain text with appropriate HTML
linebreaks(Input) when is_binary(Input) ->
- linebreaks(binary_to_list(Input));
-% a bit of a hack; unlikely, but could replace "</p>\z\z<p>" literal by mistake
+ linebreaks(binary_to_list(Input),[]);
linebreaks(Input) ->
- Input1 = re:replace(Input,"\r\n" ,"<br />", [global,{return,list}]),
- Input2 = re:replace(Input1, "\n[\n\r]+" ,"</p>\z\z<p>", [global,{return,list}]),
- Input3 = re:replace(Input2,"\r[\n\r]+" ,"</p>\z\z<p>", [global,{return,list}]),
- Input4 = re:replace(Input3,"\n" ,"<br />", [global,{return,list}]),
- Input5 = re:replace(Input4,"\r" ,"<br />", [global,{return,list}]),
- Input6 = re:replace(Input5,"</p>\z\z<p>","</p>\n\n<p>", [global,{return,list}]),
- lists:flatten(["<p>", Input6,"</p>"]).
+ linebreaks(Input,[]).
+
+linebreaks([],Acc) ->
+ "<p>" ++ lists:reverse(Acc) ++ "</p>";
+linebreaks([$\n|T], ">p<"++_ = Acc) ->
+ linebreaks(T, Acc);
+linebreaks([$\r|T], ">p<"++_ = Acc) ->
+ linebreaks(T, Acc);
+linebreaks([$\n, $\n|T],Acc) ->
+ linebreaks(T, lists:reverse("</p><p>", Acc));
+linebreaks([$\r, $\n, $\r, $\n|T],Acc) ->
+ linebreaks(T, lists:reverse("</p><p>", Acc));
+linebreaks([$\r, $\n|T], Acc) ->
+ linebreaks(T, lists:reverse("<br />", Acc));
+linebreaks([$\n|T], Acc) ->
+ linebreaks(T, lists:reverse("<br />", Acc));
+linebreaks([C|T], Acc) ->
+ linebreaks(T, [C|Acc]).
%% @doc Converts all newlines to HTML line breaks.
linebreaksbr(Input) when is_binary(Input) ->
View
6 tests/src/erlydtl_unittests.erl
@@ -442,6 +442,12 @@ tests() ->
{"|linebreaks",
<<"{{ var1|linebreaks }}">>, [{var1, "Joel\nis a slug"}],
<<"<p>Joel<br />is a slug</p>">>},
+ {"|linebreaks",
+ <<"{{ var1|linebreaks }}">>, [{var1, "Joel\n\n\n\nis a slug"}],
+ <<"<p>Joel</p><p>is a slug</p>">>},
+ {"|linebreaks",
+ <<"{{ var1|linebreaks }}">>, [{var1, "Joel\n\nis a \nslug"}],
+ <<"<p>Joel</p><p>is a <br />slug</p>">>},
{"|linebreaksbr",
<<"{{ var1|linebreaksbr }}">>, [{var1, "One\nTwo\n\nThree\n\n\n"}],
<<"One<br />Two<br /><br />Three<br /><br /><br />">>},

0 comments on commit f40805a

Please sign in to comment.
Something went wrong with that request. Please try again.