Re: [htmltmpl] enhancements to H::T
Brought to you by:
samtregar
From: Mathew R. <mat...@re...> - 2003-12-10 06:56:10
|
> > > - dot syntax, eg 'user.name' > > > >Allowing dots in variable names seems harmless enough. > <snip> >=20 >=20 > The thing is, 'user.name' isn't a variable name in the traditional=20 > way. Rather, it's saying 'I want the attribute "name" for the = variable=20 > "user"', thus providing a more OO approach. >=20 > I imagine that this would be implemented by passing an object that = provides=20 > accessors for the fields that would show up in the template. For the=20 > example above: >=20 > package My::UserVar; > use base 'HTML::Template::Var'; # For example >=20 > sub new > { > my $class =3D shift; > my $in =3D shift || { }; > return unless ref($in) eq 'HASH'; > my $self =3D { map { $_ =3D> $in->{$_} || '' } qw( name addr city = state=20 > postal )}; > bless $self, $class; > } > sub name { $_->{name} } > sub addr { $_->{addr} } > sub city { $_->{city} } > sub state { $_->{state} } > sub postal { $_->{postal} } >=20 >=20 > package main; >=20 > # $tmpl defined elsewhere, holding an HTML::Template object > my $user =3D My::UserVar->new({ name =3D> 'foo', addr =3D> 'bar' }); > $tmpl->param( user =3D> $user ); I hadn't considered doing it this way, though the idea of using a OO = styled notation appeals to me. I was thinking along the lines of: In a template you may do something like: <TMPL_IF user> <TMPL_IF user.name> <TMPL_VAR user.name.first> <TMPL_VAR user.name.last> </TMPL_IF> <TMPL_IF user.address> <TMPL_VAR user.address.street> <TMPL_VAR user.address.town> </TMPL_IF> </TMPL_IF> Normally your code would look something like: if (length $user->name->first or $user->name->last ) { $tmpl->param ('user' =3D> 1); $tmpl->param ('user.name' =3D> 1); $tmpl->param ('user.name.first' =3D> $user->name->first ); $tmpl->param ('user.name.last' =3D> $user->name->last ); } if (length $user->address->street or $user->address->town) { $tmpl->param ('user' =3D> 1); $tmpl->param ('user.address' =3D> 1); $tmpl->param ('user.address.street' =3D> $user->address->street); $tmpl->param ('user.address.town' =3D> $user->address->town); } With the 'structure_vars' support you can do this: $tmpl->param( 'user.name.first' =3D $user->name->first ); $tmpl->param( 'user.name.last' =3D $user->name->last ); $tmpl->param( 'user.address.street' =3D $user->address->street ); $tmpl->param( 'user.address.town' =3D $user->address->town ); regards, Mathew |