MadHacker
MadHacker

Reputation: 608

HTML::Template Perl

IIs there a package similar to HTml::Template in perl which takes a JSON object and maps it to a HTML template file? I am building a web application using HTML::Template and will be receiving JSOn from a web services API, things will be made simple if I can templatize this JSOn to HTML instead of doing it the exact way HTML::Template requires.

Upvotes: 1

Views: 1930

Answers (3)

tinita
tinita

Reputation: 4346

ok, a bit late, but: HTML::Template always wants a hash of arrays of hashes and so on. and you cannot navigate through the parameter stash. If you want to do this, you might try out HTML::Template::Compiled which allows you to do this.

<tmpl_var some_hash.key.another_key[23] >

or with alternative delimiters:

[%= some_hash.key.another_key[23] %]

but note the documented differences of the module to HTML::Template.

So you decode your JSON string to a data structure and pass it to the template and then you can access all values somewhere deep in the structure.

Upvotes: 1

Tudor Constantin
Tudor Constantin

Reputation: 26861

HTML::Template is a rather 'simple' templating engine - I am using quotes because its simplicity let's you do whatever you need in a view part from the Model View Controller architecture.

However, you can not execute arbitrary perl code inside a HTML::Template.

Also, due to the fact that in JSON you could have very complex data structures, I doubt that there are any suitable ways of using JSON in a straight way in your templates.

The only solution I see as possible is for you to use a Perl script that will parse the JSON, create some 'objects' and pass them to your templates. You already have that perl script - is the one that instantiate your HTML::Template object.

Upvotes: 1

Quentin
Quentin

Reputation: 943996

HTML::Template just takes a data structure consisting of strings, hashes and arrays. JSON maps directly onto that.

$template->param(myData => JSON::Any->new->decode($json_string));

Upvotes: 6

Related Questions