[英]How can I define constants in a Template Tookit template in a Catalyst app?
I want to use a constant in my TT template. 我想在TT模板中使用常量。 In HTML::Mason (my previous templating engine of choice) I could do:
在HTML :: Mason (我之前选择的模板引擎)中,我可以做:
<%once>
use MyApp::Constants qw(CONSTANT);
</%once>
How can I do this in Template Toolkit ? 如何在Template Toolkit中执行此操作? As mentioned in the title this is a Catalyst app so I was thinking I could put the constants in the stash but that seems a bit awkward.
如标题中所述,这是Catalyst应用程序,因此我认为我可以将常量放入存储库中,但这似乎有点尴尬。
--edit - 编辑
Sorry - I should have mentioned I want to use my own constants - exported from MyApp::Constants, without duplication. 抱歉-我应该提到我想使用自己的常量-从MyApp :: Constants导出,没有重复。
In your TT configuration, you can use the VARIABLES option to pass a list of values that will be passed to every template when it's processed. 在TT配置中,您可以使用VARIABLES选项传递一个值列表,该值将在处理每个模板时传递给每个模板。 Using some symbol table trickery, you can suck out all your constants into the config:
使用一些符号表技巧,您可以将所有常量都吸收到配置中:
use MyApp::Constants;
use Template;
my $tt; # template object
{
no strict 'refs';
$tt = Template->new( {
VARIABLES => { map { $_ => &{ 'MyApp::Constants::' . $_ } }
grep { defined &{ 'MyApp::Constants::' . $_ } }
keys %MyApp::Constants::
}
}
)
}
This looks at all the symbols in the package MyApp::Constants
, checks if they are defined as subroutines (this is what constant.pm
does under the hood) and then uses map
to provide a hashref of them to TT. 这将检查包
MyApp::Constants
中的所有符号,检查是否将它们定义为子例程(这是constant.pm
在后台执行的操作),然后使用map
将它们的hashref提供给TT。
Several possibilities. 几种可能性。 Just define some variables:
只需定义一些变量:
[% users = {
tom => 'Thomas',
dick => 'Richard',
larry => 'Lawrence',
}
%]
[% FOREACH u IN users %]
* [% u.key %] : [% u.value %]
[% END %]
Use the global variable: 使用全局变量:
[% global.version=1.234 %]
This is Version [% global.version %].
The META directive allows simple metadata items to be defined within a template.
META指令允许在模板中定义简单的元数据项。 These are evaluated when the template is parsed and as such may only contain simple values (eg it's not possible to interpolate other variables values into META variables).
这些是在解析模板时评估的,因此只能包含简单值(例如,无法将其他变量值内插到META变量中)。
[% META
title = 'The Cat in the Hat'
author = 'Dr. Seuss'
version = 1.23
%]
As you already mentioned in the question body, there's also this: http://template-toolkit.org/docs/manual/Variables.html#section_Compile_Time_Constant_Folding 正如您在问题正文中已经提到的,还有以下内容: http : //template-toolkit.org/docs/manual/Variables.html#section_Compile_Time_Constant_Folding
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.