Forum

Thread tagged as: Question, Suggestions, Docs

Is it possible to pass an array in to a template with set_vars

I have an array of values that I would like to pass into my template. I will not know the exact size of this array, so passing into a template file, then looping over it would be idea (possibly using perches repeaters).

Is this at all possible at present? If not, my best option may be instead of having a single html file for a page, I create one before the loop, one after, and then the one for the loop. Not ideal, but it would do the trick I think.

Dan Duke

Dan Duke 1 points

  • 6 years ago

Yes. Passing an associate array to template will loop through template.

Thanks, I nearly have it too. I have an array passed in, and the below code, but I am unsure of the best way to pull out the values I need to render. At the moment, this is printing 'boom' and the first item of the array multiple times, so imagine I just need to know how to pass in integer into the content such as id="sdata_array{i}"

<perch:repeater id="sdata_array" label="sdata array">
  <p>boom</p>
    <perch:content type="hidden" id="sdata_array" />
</perch:repeater>

Thanks for your help, Dan

Dan, I may not have had my thinking cap on straight...

I often have an array which I pass to perch_template() which it what I was thinking when I responded to your question

perch_template('content/article.html', array(
    'heading'=>'Hello world',
    'date'=>'2013-05-09 12:30:00',
));

is this something you could use?

Ah yes, I am already using something along those lines for other things, the issue is that only works when you know how many variables there are. I have an address array which could be anything from 0 to 8 lines long, and would like to pass that in with carriage returns.

An alternative could be how to pass HTML through as a variable, as at present it gets reformatted, and so prints out any <br> tags

Drew McLellan

Drew McLellan 2638 points
Perch Support

Add encode="false" to the tag to prevent already-encoded content from being double encoded.

<perch:content id="yourID" type="yourType" label="yourLabel" encode="false" />

EDIT... like Drew replied..lol while I was typing an example

perfect, thanks for that, encode="false FTW

Dan, Often if I have a template I will use only with perch_template() this is how I do it...

First, I start the template name with _underscore because this will hide template then I will use perch tags like the one in this example...

<h1>Hello <perch:content id="firstName" type="textarea" encode"false" /></h1>

Also, If I am going to pass a variable into a template being rendered with perch_content_custom() then I pass variables with

PerchSystem::set_var('var_firstName','Robert');

then in template I use

<h1>Hello <perch:content id="var_firstName" type="hidden" encode"false" /></h1>

this way if the template is re-used the fields with passed in vars will not be rendered in the admin panel.