Gossamer Forum
Home : Products : Gossamer Links : Discussions :

Passing a hash or a hash ref to template

Quote Reply
Passing a hash or a hash ref to template
 How can I pass to templates a hash or a hash ref variable?

For example: If I have an object on the page with properties Name, Size, ... then I use in templates <%Name%>, <%Size%> and the question is if is possible use of <%Object->{Name}%>, <%Object->{Size}%>
Ok, it is possible using loops but not in all cases.
Quote Reply
Re: [svalera] Passing a hash or a hash ref to template In reply to
If you can use <%Name%> why would you want <%Object->{Name}%> ?
Quote Reply
Re: [RedRum] Passing a hash or a hash ref to template In reply to
Hi!

I can have more object types with property Name, and then <%Name%> don't works, but <%Object1Name%>, <%Object2Name%> don't look effective
Quote Reply
Re: [svalera] Passing a hash or a hash ref to template In reply to
Hi,

You can't access hash's in the template. The only time you can is when you have an array of hashes, in that case you can use loops. Each time through the loop, the hash is available.

So you can do:

GT::Template->parse('file.html', { hash_loop => [ $hash1, $hash2, $hash3 ] });

<%loop hash_loop%>
Name: <%Name%>
<%endloop%>

Hope that helps,

Alex
--
Gossamer Threads Inc.
Quote Reply
Re: [Alex] Passing a hash or a hash ref to template In reply to
Hi,

but I need something else, for example

$Object1 = { Name => 'aa', Description => 'bb'}
$Object2 = { Name => 'cc', Content => 'dd'}

and the result of teplate parsing must be:

Name1: aa, Name2: cc, Description: bb, Content: dd

(template is: Name1: <%???%>, Name2: <%???%>, Description: <%???%>, Content: <%???%>)

How can I do it?
Quote Reply
Re: [svalera] Passing a hash or a hash ref to template In reply to
You could do:

GT::Template->parse ('file.html', { Name1 => $Object1->{Name}, Name2 => $Object2->{Name} ... });

and then use <%Name1%>, <%Name2%>. If the value of a tag is a hash, there is no way in the template to access it. You could use a global though:

sub {
my $tags = shift;
return "Name1: $tags->{Object1}->{Name}, Name2: $tags->{Object2}->{Name} ... ";
}

Cheers,

Alex
--
Gossamer Threads Inc.
Quote Reply
Re: [Alex] Passing a hash or a hash ref to template In reply to
Ok. Thanks.

My question was if this way is the only one.

Now, when I obtain hash refs from $sth->fetchrow_hashref from several tables with some coincident keys, I must rename this keys and it takes time Frown

Probably I will try in future to modify Template module for my needs Pirate
Quote Reply
Re: [svalera] Passing a hash or a hash ref to template In reply to
To prefix the hash, you could do:

%hash = map { 'Object1_' . $_ => $obj1->{$_} } keys %hash;

and that will prepend 'Object1_' to every key. Modifying GT::Template would not be easy. =)

Cheers,

Alex
--
Gossamer Threads Inc.