How to create a Template::Plugin::Filter to convert HTML to JS

I have a case. I have on an external site something like this :

<script src="http://mydomain/myscript"></script>

myscript is a Dancer app that need to generate an html content from a directory. Basically it is use to purpose link for a mirror. So, I could of course generate ton of "document.write" and handler anything about it. Like quoted any quote, and well. It's not really easy to create an html content from JS.

Here my idea. Create a pure HTML content, that will be filter and transform into a JS "document.write" style. I just need to create my HTML and my filter do the rest.

So here my filter :

package Template::Plugin::HTMLToJS;
use strict;
use warnings;
use 5.012;
        
use parent 'Template::Plugin::Filter';
            
sub filter {    my ($self, $text) = @_;
    $text =~ s/\n/ /gx;
    $text =~ s/\s+/ /gx;
    $text =~ s/'/'+"'"+'/gx;
    return 'document.write(\''.$text.'\');';
}           
        
1;

I use it in my Dancer app, and place it in "lib/Template/Plugin/HTMLToJS.pm".

What do this script. It take your HTML and :

  • remove all newline return (useless in html, just for reading)
  • remove all space multispace and replace it by only one space
  • replace quote by a form that will be use with document.write
  • and return document.write of the transformed text

To use it in your template :

[% USE HTMLToJS %]
[% FILTER $HTMLToJS %]
<p>It's work !<p>
<ul>
<li>This is cool !</li>
</ul>
[% END %]

In my case multiple space could be delete by if you need to keep it, you could just remove the return and make the quote magic stuff. It will work too.

So the result :

document.write('<p>It'+"'"+'s work !<p> <ul> <li>This is cool !</li> </ul>');

Voila !

Have fun !

Short URL

Comments