Permalink
Browse files

Added text virtual methods: squote and dquote

  • Loading branch information...
abw committed Feb 7, 2012
1 parent 09e0b48 commit 8a7cf607647b561a09c217f0e7aab721f47d3679
Showing with 51 additions and 5 deletions.
  1. +16 −0 lib/Template/Manual/VMethods.pod
  2. +18 −1 lib/Template/VMethods.pm
  3. +17 −4 t/vmethods/text.t
@@ -57,6 +57,14 @@ Returns true if the value is defined.
[% user = get_user(uid) IF uid.defined %]
+=head2 dquote
+
+Returns the text with any double quote characters escaped with a backslash
+prefix. Any newline characters in the text will be replaced with "\n".
+
+ [% quote = 'He said "Oh really?"' %]
+ [% quote.dquote %] # He said \"Oh really?\"
+
=head2 hash
Return the value as a hash reference containing a single entry with
@@ -215,6 +223,14 @@ C<$replacement>. The substring removed from the string is then returned.
[% str.substr(0, 11, 'FOO') %] # foo bar baz
[% str %] # FOO wiz waz woz
+=head2 squote
+
+Returns the text with any single quote characters escaped with a backslash
+prefix.
+
+ [% tim = "Tim O'Reilly" %]
+ [% tim.squote %] # Tim O\'Reilly
+
=head2 trim
Returns the text with any leading and trailing whitespace removed.
View
@@ -56,7 +56,8 @@ our $TEXT_VMETHODS = {
substr => \&text_substr,
trim => \&text_trim,
collapse => \&text_collapse,
-
+ squote => \&text_squote,
+ dquote => \&text_dquote,
};
our $HASH_VMETHODS = {
@@ -304,6 +305,22 @@ sub text_substr {
}
}
+sub text_squote {
+ my $text = shift;
+ for ($text) {
+ s/(['\\])/\\$1/g;
+ }
+ return $text;
+}
+
+sub text_dquote {
+ my $text = shift;
+ for ($text) {
+ s/(["\\])/\\$1/g;
+ s/\n/\\n/g;
+ }
+ return $text;
+}
#========================================================================
# hash virtual methods
View
@@ -52,16 +52,13 @@ my $params = {
word => 'bird', # The bird is the word
WORD => 'BIRD',
the_bird => "\n The bird\n is the word \n ",
+ quotable => "Tim O'Reilly said \"Oh really?\"",
};
test_expect(\*DATA, undef, $params);
__DATA__
-#------------------------------------------------------------------------
-# defined
-#------------------------------------------------------------------------
-
-- test --
-- name text.defined implicit undef --
[% notdef.defined ? 'def' : 'undef' %]
@@ -183,6 +180,22 @@ The cat sat on the mat
-- expect --
1
+-- test --
+-- name text.squote --
+[% quotable %]
+[% quotable.squote %]
+-- expect --
+Tim O'Reilly said "Oh really?"
+Tim O\'Reilly said "Oh really?"
+
+-- test --
+-- name text.dquote --
+[% quotable %]
+[% quotable.dquote %]
+-- expect --
+Tim O'Reilly said "Oh really?"
+Tim O'Reilly said \"Oh really?\"
+
-- test --
-- name text.repeat --
[% animal.repeat(3) %]

0 comments on commit 8a7cf60

Please sign in to comment.