Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Import Constants From File to Templates?

by haj (Vicar)
on Dec 04, 2021 at 17:09 UTC ( [id://11139390]=note: print w/replies, xml ) Need Help??


in reply to Import Constants From File to Templates?

In your current implementation you could (ab)use the EXPORTS_OK list to import the constants as template variables:

my $content_ref = { map { $_ => Sam::Constants->$_ } @Sam::Constants::EXPORT_OK }

You could also pre-load them into the configuration of your >TT object. Here's a complete example:

use strict; use warnings; package Sam::Constants; use base 'Exporter'; use constant PRE => 1; use constant REGULAR => 2; use constant POST => 3; our @EXPORT_OK = qw( PRE REGULAR POST ); package main; use Template; my $text = <<EOT; The constant 'PRE' has the value [% PRE %] The constant 'REGULAR' has the value [% REGULAR %] The constant 'POST' has the value [% POST %] EOT my $tt = Template->new( { VARIABLES => { map { $_ => Sam::Constants->$_ } @Sam::Constants::EXPORT_OK }, } ) || die "$Template::ERROR\n"; $tt->process( \$text ) || die $tt->error(), "\n";
When run, this prints:
The constant 'PRE' has the value 1 The constant 'REGULAR' has the value 2 The constant 'POST' has the value 3

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139390]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-04-19 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found