Closed srchulo closed 10 years ago
We can add such functions easily(Patch is https://gist.github.com/syohex/11164994).
However are they really necessary as built-in array functions ?
We can access first and last element by indexing 0
, -1
respectively.
print $tx->render_string('first: <: $data[0] :>, last: <: $data[-1] :>',
{
data => [1..10]
});
Or we can add such functions by specifying function
parameter of constructor as below.
use Text::Xslate;
my $tx = Text::Xslate->new(
function => {
'array::first' => sub { $_[0]->[0] },
'array::last' => sub { $_[0]->[-1] },
},
);
print $tx->render_string('first: <: $data.first() :>, last: <: $data.last() :>',
{
data => [1..10]
});
print "\n";
We got following.
first: 1, last: 10
Any suggestions ?
That's a good point that you can just use 0 and -1 indices to access first and last. I guess the only benefit to first and last is that it could be more readable for people who aren't coders. My designers have to deal with these templates and "first" and "last" are probably easier for them to understand than "0" or "-1". I guess the only thing really added is it reads more like english instead of code.
I got it.
How about @gfx ? I'm ready for adding this feature.
@srchulo Can you give me an example that demonstrates the benefit of first
and last
? I know they are useful if you use them frequently, but I don't know that situation.
@gfx First and last tend to be useful a lot of times when I have an array that is sorted in order, because then the first and last items usually have some special meaning. A simple example where I needed it recently was for an ecommerce site I had a category path showing the category subsections for a page that showed all products in a category. So for the category T-Shirts:
Apparel > Men's > T-Shirts
And since the most relevant category for this page was "T-Shirts", I needed to access the last item to display it as a header at the top of the page. In this example I would use:
However, as @syohex pointed out you could also do
It would just be a "more readable" way of doing it-- depending on who's reading it :)
@srchulo LGTM. I'll add first and last in the build-in methods.
@srchulo first
and last
had been implemented and merged to master branch.
Please wait next release.
Great! Thanks @syohex and @gfx!
It would be nice to have last and first supported for TTerse as they are in Template::Toolkit, meaning that last would return the last element of the array and first would return the first element.