Peter Eberle
Peter Eberle

Reputation: 1181

Add Variable to Smarty Capture block without php

i trying to understand smarty's capture system. In my case i don't have access to php and smarty is in some sort of safe mode. And i also can't use includes because i can't create new files.

So i kind of want to declare Html Parts which i can use as "template" in an template.

what i want:

// Here i define the smarty Block which i want to use multiple times
{capture name="test"}
  <h1>{$item_type}</h1>
{/capture}

// foreach ...
{foreach [...]}
  {if $someVariable eq 0}
    {assign var="var_item_type" value="test"}
  {elseif $someVariable eq 1}
    {assign var="var_item_type" value="another test"}
  {/if}

  // here i want to Output the Block with the Variable
  {$smarty.capture.test}

{/foreach}

But right now its not working. There's no output at all.

Upvotes: 1

Views: 2720

Answers (2)

jpaljasma
jpaljasma

Reputation: 1612

Use Smarty capture into template variable (assign=popText is important):

{capture name=some_content assign=popText}
{capture some_content assign=popText} {* short-hand *}
The server is {$my_server_name|upper} at {$my_server_addr}<br>
Your ip is {$my_ip}.
{/capture}
<a href="#">{$popText}</a>

http://www.smarty.net/docs/en/language.function.capture.tpl

Upvotes: 1

Borgtex
Borgtex

Reputation: 3245

It won't work, because the variable $item_type is processed as son as you output it inside the capture block - so is empty, and all you get is <h1></h1>

The good news is that if you're using smarty 3, you can use {function} and do this:

{function titlefy}
<h1>{$text}</h1>
{/function}

and call it later anywhere you want like this:

{titlefy text=$var_item_type}

EDIT: So it turns out you're using Smarty 2... Well, not all hope is lost. You can try to sort of create a subtemplate engine using identifiers where you want the variables and replacing them later:

{capture name="test"}
   <h1>%title</h1>
   <h2>%subtitle</h2>
{/capture}

and call it with:

{$test|replace:'%title':$var_item_type|replace:'%subtitle':'something else'}

Not an ideal solution but given the constraints, this may be useful if the block of code is several lines long and you need to use it in more than one place

Upvotes: 1

Related Questions