@@ -403,6 +403,15 @@ pub fn modulo(input: &Value, args: &[Value]) -> FilterResult {
403
403
}
404
404
}
405
405
406
+ /// Replaces every newline (`\n`) with an HTML line break (`<br>`).
407
+ pub fn newline_to_br ( input : & Value , args : & [ Value ] ) -> FilterResult {
408
+ try!( check_args_len ( args, 0 ) ) ;
409
+ match * input {
410
+ Str ( ref x) => Ok ( Str ( x. replace ( "\n " , "<br />" ) ) ) ,
411
+ _ => Err ( InvalidType ( "String expected" . to_owned ( ) ) ) ,
412
+ }
413
+ }
414
+
406
415
/// Returns the number of already escaped characters.
407
416
fn nr_escaped ( text : & str ) -> usize {
408
417
for prefix in & [ "lt;" , "gt;" , "#39;" , "quot;" , "amp;" ] {
@@ -875,6 +884,31 @@ mod tests {
875
884
assert_eq ! ( unit!( modulo, Num ( 183.357 ) , & [ Num ( 12_f32 ) ] ) , Num ( 3.3569946 ) ) ;
876
885
}
877
886
887
+ #[ test]
888
+ fn unit_newline_to_br ( ) {
889
+ let input = & tos ! ( "a\n b" ) ;
890
+ let args = & [ ] ;
891
+ let desired_result = tos ! ( "a<br />b" ) ;
892
+ assert_eq ! ( unit!( newline_to_br, input, args) , desired_result) ;
893
+ }
894
+
895
+ #[ test]
896
+ fn unit_newline_to_br_one_argument ( ) {
897
+ let input = & tos ! ( "a\n b" ) ;
898
+ let args = & [ Num ( 0f32 ) ] ;
899
+ let desired_result = FilterError :: InvalidArgumentCount ( "expected 0, 1 given" . to_owned ( ) ) ;
900
+ assert_eq ! ( failed!( newline_to_br, input, args) , desired_result) ;
901
+ }
902
+
903
+ #[ test]
904
+ fn unit_newline_to_br_hello_world ( ) {
905
+ /// First example from https://shopify.github.io/liquid/filters/newline_to_br/
906
+ let input = & tos ! ( "\n Hello\n World\n " ) ;
907
+ let args = & [ ] ;
908
+ let desired_result = tos ! ( "<br />Hello<br />World<br />" ) ;
909
+ assert_eq ! ( unit!( newline_to_br, input, args) , desired_result) ;
910
+ }
911
+
878
912
#[ test]
879
913
fn unit_escape ( ) {
880
914
assert_eq ! ( unit!( escape, tos!( "Have you read 'James & the Giant Peach'?" ) ) ,
0 commit comments