Smarty Forum Index Smarty
The discussions here are for Smarty, a template engine for the PHP programming language.

Global variable scope issue

 
Post new topic   Reply to topic    Smarty Forum Index -> Smarty Development
View previous topic :: View next topic  
Author Message
Girish
Smarty Rookie


Joined: 05 Jan 2017
Posts: 5

PostPosted: Fri Jan 13, 2017 11:45 am    Post subject: Global variable scope issue Reply with quote

Code:
{function name=testing data=''}
   {assign var=var_a value=$data scope="global"}
{/function}

{testing data=1}
1. {$var_a}

{testing data=2}
2. {$var_a}


Expected Output:
1. 1
2. 2

Actual Output:
1. 1
2. 1

What is wrong with this?
Back to top
View user's profile Send private message
bsmither
Smarty Regular


Joined: 20 Dec 2011
Posts: 73
Location: Rocky Mountains

PostPosted: Sat Jan 14, 2017 12:14 am    Post subject: Reply with quote

I think the use of scope is not applicable here. Scope wants to have the variable and value be seen in the template hierarchy (that is, included sub-templates), not the logical hierarchy (that is, functions).

So, we should accept that variables created or modified inside a Smarty function will not be known outside that function.

Also, unlike a PHP function where arguments are input to get an output that can be used elsewhere, a Smarty function does not output anything other than the actual textual rendering of its task.

So, try:
Code:

{function testing} {* short-form *}
   {$data}
{/function}

1. {testing data=1}
2. {testing data=2}
Back to top
View user's profile Send private message
Girish
Smarty Rookie


Joined: 05 Jan 2017
Posts: 5

PostPosted: Mon Jan 16, 2017 8:22 am    Post subject: Reply with quote

You mean variable scope is only limited with template hierarchy?

We want to use those variable at multiple places so if we go with this approach we have to call respective function at many times.

Can't we just return an array from function and that array I can use to array to display respective values or do we have alternative for same?
Back to top
View user's profile Send private message
AnrDaemon
Administrator


Joined: 03 Dec 2012
Posts: 927

PostPosted: Tue Jan 17, 2017 1:42 pm    Post subject: Reply with quote

Just assign a value to the template object.
Don't invent wheels.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Smarty Forum Index -> Smarty Development All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP