|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
N1CK3RS0N Smarty Regular
Joined: 04 Mar 2009 Posts: 41
|
Posted: Thu Aug 14, 2014 3:38 am Post subject: Using Javascript in .tpl file to select a $smarty variable? |
|
|
Question is posted here.
http://stackoverflow.com/questions/25299419/javascript-variable-in-php-array-variable
Basic summary: Can I use a JavaScript loop in a .tpl file such as below where I can select an array from a smarty variable using the JavaScript variable?
Code: |
<script type="text/javascript">
for( i = 1; i < 4; i++ ) {
{$example_array.i}
}
</script>
|
Any thoughts?[/code] |
|
Back to top |
|
AnrDaemon Administrator
Joined: 03 Dec 2012 Posts: 1785
|
|
Back to top |
|
U.Tews Administrator
Joined: 22 Nov 2006 Posts: 5068 Location: Hamburg / Germany
|
Posted: Fri Aug 15, 2014 2:47 am Post subject: |
|
|
The general problem is that Smarty is running on the server an Javascript on the client. So you can use only the text output of Smarty within Javascript as a string.
A possible solution could be to use {capture} to generate a section of output which may contain loops on Smarty variables which is saved in a variable.
Code: | {capture name='some_content'' assign='content'}
// place content cotaining Smarty loops here
{/capture} |
Now you can insert {$content} in your Javascript code.
As {$content} is text inserted there before all gets send to the client it may contain also part of your Javascript code.
It may sound ugly but is a workaround.
See http://www.smarty.net/docs/en/language.function.capture.tpl |
|
Back to top |
|
douglassdavis Smarty Junkie
Joined: 21 Jan 2008 Posts: 541
|
Posted: Sat Aug 16, 2014 2:46 am Post subject: |
|
|
You may be able to use json_encode, depending on what you are trying to do.
as an example, you could do something like this
Code: |
<script type="text/javascript">
var myArray = <{$template_var|json_encode}>;
for( i = 0; i < myArray.length; i++ ) {
alert(myArray[i]);
}
</script>
|
for smarty 2 you would need this change:
Code: |
var myArray = <{$template_var|@json_encode}>;
|
|
|
Back to top |
|
|
|
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
|