Page 1 of 1

Find a single element in a Smarty array [solved]

Posted: Sun Nov 13, 2011 2:51 pm
by billandsonia
In the Add/Edit an Event form, the CGCalendar module loops over the $categories array like this:

Code: Select all

{foreach from=$categories item='category'}
<div class="row">
  <p class="row_prompt">{$category->name}:</p>
  <p class="row_input">
    {$category->field}
  </p>
</div>
{/foreach}
I am trying to work with just one of the category names - I want to be able to access each category name directly, without a loop, and to understand how to access that. I've tried the following (and at least the same number of other variations) with no success (no output). I don't think the first element is null or blank, because the array above throws out 'General' as the first result.

Code: Select all

{$categories->name.0}
{$categories->name[0]}
{$categories.0->name}
{$categories[0]->name}
{$categories->name}
{$categories[$name.0]}
{$categories[$name].0}
{$categories.0.$name}
{$categories.name.0}
I need to stop bashing my head against the wall now... all of the documentation is good at explaining how to loop over an array, not how to access an individual element.

Re: Find a single element in a Smarty array

Posted: Sun Nov 13, 2011 5:11 pm
by spcherub
This works:

Code: Select all

{$categories[1]->name}
For some reason the $categories array is not zero-based. So if you have three categories defined, their names can be accessed as follow:

Code: Select all

{$categories[1]->name}
{$categories[2]->name}
{$categories[3]->name}
The best way to figure this out for other variables is to use a print_r smarty modifier, so something like this (below) will tell you exactly how the variable is structured:

Code: Select all

<pre>{$categories|@print_r}</pre>
Hope that helps.

-S

Re: Find a single element in a Smarty array [solved]

Posted: Sun Nov 13, 2011 8:57 pm
by billandsonia
Thanks, spcherub!

Two lessons I needed to be reminded of:

1) Double-check the obvious

2) Don't assume