Using a variable to access hash keys in Template Toolkit - perl

I have an array whose contents is
$VAR1 = {
'1' => 'May 05, 2011',
'0' => 'Jul 22, 2009',
'2' => 'Jun 13, 2012'
};
I am trying to display it in the catalyst template, the code is
[% x = 0 %]
[% FOREACH mortgage IN mortgages %]
<table width=40% border=1 cellspacing="0" cellpadding="10">
<tr>
<td>Date</td>
<td><b>[% dateformat.x %]</b></td>
</tr>
</table>
[% x = x+1 %]
[% END %]
The dateformat.x should display May 05, 2011 or Jul 22, 2009 or Jun 13, 2012 according to the value of x but the error is that it displays nothing. It shows a blank .
The error I think is that the key in the array is a string while the value of x that is used with the dateformat is numeric. If I add 0 or 1 with the dateformat then it displays correctly([% dateformat.0 %]).

[% dateformat.x %] looks in the dateformat hash for a key of x. To tell template toolkit that x is a variable, prefix it with $:
[% dateformat.$x %]
To access a hash entry using a key stored in another variable, prefix the key variable with '$' to have it interpolated before use (see Variable Interpolation).

I appreciate this question has already been asked and answered, but a handy alternative is the item() VMethod. This is particularly effective when you have hash keys that conflict with VMethods:
[%- SET myhash = { last => 'Blues', first => 'Elwood',
address => '1060 West Addison', city => 'Chicago' };
myhash.first; # doesn't do what you want,
# because first is a VMethod for 1st element in an array
myhash.item('first'); # displays "Elwood"
-%]
VMethods like first, last, size and sort are common traps for the unwary here.

Related

show some data in koha ILS authority normal view

in opac-authoritiesdetail.pl
i add
$template->param( "tag_781_z" => $record->subfield('781','z') );
and in opac-auth-detail.tt
[% IF( tag_781_z ) %]
<span class="">
<span class="label">Geographic Subdivision
</span>
[% tag_781_z %]
</span>
[% END %]
the result
the first value only shown
but I add 3 value
If field 780$z is repeatable you must add value this field to array.
Regards

Why this line stops Sphinx search?

I use sanitizing from example: Barryhunter's
But when I use the line:
$q = preg_replace('/[^\w~\|\(\)\^\$\?"\/=-]+/',' ',trim(strtolower($q)));
then Russian search don't works! Only English.
What the reason? How I should use sanitizing?
This is my piece:
<HTML>
<BODY>
<form action="" method="get">
<input name="q" size="40" value="<?php echo #$_GET['q']; ?>" />
<input type="submit" value="Search" />
</form>
<?php
require ( 'sphinxapi.php' );
$sphinx = new SphinxClient;
$sphinx->SetServer('ununtu', 9312);
$sphinx->open();
$sphinx->SetMatchMode (SPH_MATCH_EXTENDED);
$sphinx->setFieldWeights(array(
'title' => 10,
'content' => 5
));
$sphinx->SetRankingMode(PH_RANK_WORDCOUNT);
$sphinx->SetSortMode(SPH_SORT_RELEVANCE);
$sphinx->setLimits(0, 10, 200);
$sphinx->resetFilters();
$q = isset($_GET['q'])?$_GET['q']:'';
$q = preg_replace('/ OR /',' | ',$q);
// $q = preg_replace('/[^\w~\|\(\)\^\$\?"\/=-]+/',' ',trim(strtolower($q)));
if(isset($_GET['q']) and strlen($_GET['q']) > 1)
{
$result = $sphinx->query($sphinx->escapeString($q), '*');
...
Assuming your input string is utf-encoded you use non-unicode preg_replace. Add 'u' in the end, e.g.:
$q = preg_replace('/[^\w~\|\(\)\^\$\?"\/=-]+/u',' ',trim(strtolower($q)));
Specifically that regex is stripping anything that is not a 'word' char, or a predefined list of syntax/punctuation chars.
The PREG definition of word (the \w ) is
A "word" character is any letter or digit or the underscore character,
that is, any character which can be part of a Perl "word". The
definition of letters and digits is controlled by PCRE's character
tables, and may vary if locale-specific matching is taking place. For
example, in the "fr" (French) locale, some character codes greater
than 128 are used for accented letters, and these are matched by \w.
http://php.net/manual/en/regexp.reference.escape.php
So possibly in English locale (or other western European for example), hence many Russian chars are not considered a word char, and stripped.
(if your pages are in UTF8, then may also need the /u as mentioned by other answer)

How to pass arguments to a subroutine in template toolkit function

I my document foo.tt i would like to write something like this:
[% INCLUDE header('str', 1, 2, 3, 5, 10) %]
My aim is to do some string manipulation on str and then with foreach / for iterates over all the numbers.
unfortunately i was unable to find that this type of syntax in Template toolkit is allowed.
What is Template toolkit way for passing arguments to a subroutine?
Any ideas how to do it?
You can pass arguments, but you need to give them names. Example:
outer.tt2:
[% INCLUDE header.tt2 header_string="str", items=[ 1, 2, 3, 5, 10 ] -%]
header.tt2:
String: [% header_string %]
[% FOREACH item IN items -%]
Item: [% item %]
[% END -%]
output:
String: str
Item: 1
Item: 2
Item: 3
Item: 5
Item: 10
Check out MACRO definitions:
[% MACRO header(str, items) BLOCK -%]
[% FOREACH i IN items; -%]
... your item code here ...
[% END -%]
[% END -%]
[% header('str',[1, 2, 3, 5, 10]) %]
If TT exposed the raw arguments list at the template level, you could call it as you indicated (e.g. header('str', 1, 2, 3, 5, 10)), but this is pretty close.

Hash Dereference in Template Toolkit

I've got a multi-dimensional hash that I'm trying to print out in a table. I can't get the referencing / dereferencing right.
I'm putting an excel spreadsheet into the hash and I want to print out the corresponding rows and columns in html and match the rows/columns of the spreadsheet (some of which are empty).
I'm using Perl Dancer and Template Toolkit. On the server side the hash works fine. print $big_table{$column}{$row}; on the server side and it prints the correct column and row with NO issues.
On the client side, the 0, 1, 2... are supposed to be the columns. Some columns are blank so I can't just print the contents.
The way it is now it prints ARRAY(0x3e5389c). I tried a different way and it printed HASH...
I know I've got some reference/dereference issues. Any advice would be welcome.
Server Side Code:
my %big_table = ();
# $cell->value() is the text ripped from the excel cell at that location
$big_table{$column}{$row} = $cell->value();
template 'index', { big_table => \%big_table };
Client Side:
<Table border="3">
<% FOREACH n IN big_table.0 %>
<TR><TD>&nbsp<% big_table.0.keys %>&nbsp<TD>&nbsp<% big_table.1.keys %>
&nbsp<TD>&nbsp<% big_table.2.keys %>&nbsp<TD>&nbsp<% big_table.3.keys %>
&nbsp <TD>&nbsp<% big_table.4.keys %>
&nbsp<TD>&nbsp<% big_table.5.keys %>&nbsp
<% END %>
</Table>
Thanks in advance!
Got it working.
Changed to an array. '$big_table[$col][$row] = $cell->value();' and populated a second array with all the row #'s.
The Client looks like
<% FOREACH r IN row_numbers %>
<TR><TD> &nbsp <% big_table.0.$r %> &nbsp <TD> &nbsp <% big_table.1.$r %>...
<% END %>
Works great but it's probably crazy in-effecient :(. The spreadsheet is 800 rows long so it's a 2nd array with 800 elements just to iterate over 'FOREACH' loop.

XML::Simple removes root element

Hi I have a xml data which i get from array of hashes and when I do a Dumper on it the output is as follows:
$var1=
'<Data>
<Data1>ABC</Data1>
<Data2>ABCD</Data2>
</Data>';
This I have in a variable call $var1. Now I am using XML::Simple on it.. it is somewhat like: {Data1=>'ABC',Data2=>'ABCd'};
The first tag Data is gone. What is wrong?
Seems to be well-documented:
KeepRoot => 1:
In its attempt to return a data structure free of superfluous detail
and unnecessary levels of indirection, XMLin() normally discards the
root element name. Setting the KeepRoot option to 1 will cause the
root element name to be retained. So after executing this code:
$config = XMLin('<config tempdir="/tmp" />', KeepRoot => 1)
You'll be able to reference the tempdir as
"$config->{config}->{tempdir}" instead of the default
"$config->{tempdir}".