1 package SL::Template::Plugin::JavaScript;
3 use base qw( Template::Plugin );
9 my ($class, $context, @args) = @_;
20 # see ecmascript spec section 7.8.4
21 my @escape_chars = ('\\', '\'', '"');
28 "\x0B" => 'v', # noone uses vertical tab anyway...
30 my $re = join '', map { qr/($_)/s } join '|', keys(%control_chars), map { "\Q$_\E" } @escape_chars;
36 $text =~ s/$re/'\\' . ($control_chars{$1} || $1)/egs;
42 return _replace_helper('replaceWith', @_);
45 sub replace_html_with {
46 return _replace_helper('html', @_);
54 die 'not an accessor' if @_ > 1;
55 return $_[0]->{CONTEXT};
59 my ($method, $self, $selector, $template, $locals) = @_;
61 $template .= '.html' unless $template =~ m/\.html$/;
62 my $html = $self->escape($self->_context->process($template, %{ $locals || { } }));
64 \$('${selector}').${method}("$html");
81 SL::Template::Plugin::JavaScript - Template plugin for JavaScript helper functions
87 =item C<escape $value>
89 Returns C<$value> escaped for inclusion in a JavaScript string. The
90 value is not wrapped in quotes. Example:
92 <input type="submit" value="Delete"
93 onclick="if (confirm('Do you really want to delete this: [% JavaScript.escape(obj.description) %]') return true; else return false;">
95 =item C<replace_with $selector, $template, %locals>
97 Returns code replacing the DOM elements matched by C<$selector> with
98 the content rendered by Template's I<PROCESS> directive applied to
99 C<$template>. C<%locals> are passed as local parameters to I<PROCESS>.
101 Uses jQuery's C<obj.replaceWith()> function. Requires jQuery to be loaded.
107 <li id="item1">First item</li>
108 <li id="item2">Second item</li>
109 <li id="item3">Another item</li>
112 <script type="text/javascript">
114 [% JavaScript.replace_with('#item2', 'todo/single_item', item => current_todo_item) %]
118 <input type="submit" onclick="do_work(); return false;" value="Replace single item">
120 =item C<replace_html_with $selector, $template, %locals>
122 Returns code replacing the inner HTML of the DOM elements matched by
123 C<$selector> with the content rendered by Template's I<PROCESS>
124 directive applied to C<$template>. C<%locals> are passed as local
125 parameters to I<PROCESS>.
127 Uses jQuery's C<obj.html()> function. Requires jQuery to be loaded.
131 <li id="item1">First item</li>
132 <li id="item2">Second item</li>
133 <li id="item3">Another item</li>
136 <script type="text/javascript">
138 [% JavaScript.replace_html_with('#todo_list', 'todo/full_list', items => todo_items) %]
142 <input type="submit" onclick="do_work(); return false;" value="Replace list">
152 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>