mschout / perl-text-template

Expand template text with embedded Perl
13 stars 6 forks source link

writing functions ? #17

Closed richsalz closed 4 years ago

richsalz commented 4 years ago

I know I can reference variables defined in modules that are loaded before invoking the text::template stuff. That is, if the PACKAGE is "OpenSSL::safe", then my module can have "OpenSSL::safe::bar" and I can reference it was "{- $OpenSSL::safe::bar -}" in my files.

Can I write functions (in the module) and call them in my templates?

mschout commented 4 years ago

Yes, of course. e.g.:

use Text::Template 'fill_in_string';
use POSIX ();

say fill_in_string(<<~'END');
  { POSIX::ceil(1.1) }
  END
richsalz commented 4 years ago

Sorry, I wasn't clear. I have a perl module (docvars.pm) that is -M imported before my utility script, that calls the Text::Template stuff, runs. I would like to define a function in docvars.pm and then use it in the files that I call text::template on.

This is in an OpenSSL PR, https://github.com/openssl/openssl/pull/10159, which might be useful or might not.

mschout commented 4 years ago

That PR is pretty large, and I don't have time at moment to digest, but yes, you can define functions in the package that Text::Template uses to fill in and call them, assuming that is what you are asking. It works.

package X;

$foo = 'bar';

sub hello {
    'world'
}

package main;

use 5.024;

use Text::Template 'fill_in_string';

say fill_in_string(<<~'EOT', package => 'X');
    { $foo }
    { X::hello() }
    EOT

Yields:

bar
world
richsalz commented 4 years ago

Yeah, I figured it was more than you had time to digest. Thanks.