Smilyan Pavlov

Designer & web strategy consultant in sheffield, uk, smarty – how to assign a variable into a variable in the template.

Recently I needed to assign several variables into one smarty variable inside the template.

Here is the basic rules for the example:

  • You have a text that says “Your registration expires in # days”;
  • You want The text “in # days” to change to “today” if the # days is 0.

Here’s a way you can do this with smarty variables inside the template (whether you should do this in the template is not a discussion for this post).

The key here is that when you want to include a variable as part of the value of another variable you need to use value=” $in_days “ . Notice the  ` before and after the variable name inside the double quotes. You can use this method to include variables inside value statements anywhere in smarty templates and make modifications of those included variables.

One thought on “ Smarty – How to assign a variable into a variable in the template ”

That helped a lot. Thanks!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Smarty variables inside JS files

I understand using tpl files and variables inside such files.

Issue is how to manage variables also inside js file. If I add JS file like the following line:

How to add also variables inside JS file. Is there good example to do this?

In this case it will not work like tpl file

// {/literal}{$variablesmng.myvariable1}{literal}, {/literal}{$variablesmng.myvariable2}{literal}),

If you’re having that much problems with Smarty, maybe it’s better to use a template engine that does not have such problems.

PHP is server-side and jQuery client-side. When I use tpl file it will be detected smarty variable. When I insert JS file and add smarty variable it will not detect. Another framework will not solve this but probably can be solved in some way using Smarty.

Do you have example as JS file that there are included variables? just sample…

Can you be more clear what you want to achieve? First you say you want template variables inside js files and next you show an example of an inline script in a html file. I’m confused.

Normally, you don’t use template variables in plain js files but you can pass them into js via normal html templates:

If you wanted variables inside the external.js file then you could do it but you’d need to create a separate template for it and invoke it from a separate php script. However, I think in most cases it would be overkill and I would prefer to simply pass the variables through the html template like in the example above.

Will you share some more specifics? As far as I know all template engines behave the same way regarding js - it would be interesting to know what kind of js features are available in engines other than Smarty?

Thank you for your example. Sorry if it was not clear. It will solve many issues if can be done. See please real example. TPL file is using Javascript code. In this example I have to insert PHP values due to applications.

Now I have to insert also server value inside pure Javascript file and many ID’s. How to solve this in real example? ID’s are values like 40.781840, -73.972967

This one is fine but in Smarty 3 you don’t have to use all those {literal} tags - they can make your code difficult to read. If you put a space or newline after { then you don’t need {literal}:

Pass the php values from your html template, the same one where you include the external js file:

googleMapDemo.js now doesn’t need any php variables (see marker1 ):

In this example I used the GoogleMapDemo object created earlier in the external js file and I inserted the variables to this object. But if you don’t have an object like this you can do the same with global variables, or better yet create a special object for passed variables from php just for readability:

And in googleMapDemo.js replace your numeric values with references to this object like passedVars.centerLat , passedVars.lat1 , passedVars.lng2 , etc.

This way you leave your external js file a simple static file without any php or template variables - this is good for performance since loading the js file will not consume (almost) any CPU cycles.

The main problem I experienced is that you can read a perfectly fine JavaScript object as Smarty variable, due to the use of single { } as variable’s delimiters. counter example from Twig, where {{ }} are used, objects cannot be mistaken as variables.

Thank you. will test.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.

  • Combining Modifiers
  • {config_load}
  • {if},{elseif},{else}
  • {ldelim},{rdelim}
  • {setfilter}
  • Config Files
  • Debugging Console

{assign}, {$var=...}

{assign} or {$var=...} is used for assigning template variables during the execution of a template .

Attributes of the {assign} syntax

Attributes of the {$var=...} syntax, option flags.

Note Assignment of variables in-template is essentially placing application logic into the presentation that may be better handled in PHP. Use at your own discretion.

The above example will output:

{ assign var = "name" value = "Bob" nocache } { * or * } { assign "name" "Bob" nocache } { * short-hand, or * } { $name = 'Bob' nocache } The value of $name is { $name } . The above example will output: The value of $name is Bob.

Variables assigned in the included template will be seen in the including template.

The template above includes the example sub_template.tpl below:

You can assign a variable to root of the current root tree. The variable is seen by all templates using the same root tree.

A global variable is seen by all templates.

To access {assign} variables from a php script use getTemplateVars() . Here's the template that creates the variable $foo .

The template variables are only available after/during template execution as in the following script.

The following functions can also optionally assign template variables: {capture} , {include} , {insert} , {counter} , {cycle} , {eval} , {fetch} , {math} and {textformat} .

See also {append} , assign() and getTemplateVars() .

CMS Made Simple Forums

Content management as it is meant to be

Skip to content

  • Home Board index Community Boards The Lounge

[Solved] assigning a javascript value to Smarty?

Dev Team Member

Post by JohnnyB » Wed Feb 26, 2014 8:10 pm

User avatar

Re: Has anyone tried assigning a javascript value to Smarty?

Post by velden » Wed Feb 26, 2014 8:41 pm

Post by JohnnyB » Wed Feb 26, 2014 9:54 pm

Post by calguy1000 » Wed Feb 26, 2014 10:20 pm

Post by JohnnyB » Thu Feb 27, 2014 12:09 am

calguy1000 wrote: typically this is done by using a session cookie

Javascript – Assign JavaScript variable to Smarty variable

javascript php smarty

Possible Duplicate: how to assign a javascript variable to a smarty variable

I want to assign a textfield value to Smarty variable using JavaScript and call Smarty function but I could not do it.

Please guide me.

Best Solution

You cannot do that in an easy way. PHP, and by extension Smarty, is parsed and run on the server side before the browser get the data. JavaScript is run on the client side when the browser parses the HTML, CSS and Javascript that the server sent.

You will have to make a new HTTP request in some way, sending the new data. You can do that by reloading the entire web page and sending stuff in the querystring (after ? in the URL), or slightly more advanced by doing an Ajax call from your JS code and make JS do the changes of the page that you desire. The latter is more complex and requires some knowledge of Javascript, but the page does not need to be reloaded in its entirety.

Related Solutions

Javascript – how do javascript closures work.

A closure is a pairing of:

  • A function, and
  • A reference to that function's outer scope (lexical environment)

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret :

In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.

And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.

If JavaScript did not have closures, then more states would have to be passed between functions explicitly , making parameter lists longer and code noisier.

So, if you want a function to always have access to a private piece of state, you can use a closure.

...and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.

In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner , after it has been returned from foo .

Uses of Closures

Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.

Private Instance Variables

In the following code, the function toString closes over the details of the car.

Functional Programming

In the following code, the function inner closes over both fn and args .

Event-Oriented Programming

In the following code, function onClick closes over variable BACKGROUND_COLOR .

Modularization

In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.

This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves . It is as though the stack-frame stays alive in memory even after the outer function exits.

In the following code, three methods log , increment , and update all close over the same lexical environment.

And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x , and a new set of functions ( log etc.) are created, that close over this new variable.

If you are using variables declared using var , be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const .

In the following code, each time around the loop, a new function inner is created, which closes over i . But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.

Final points:

  • Whenever a function is declared in JavaScript closure is created.
  • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval('var foo = …') .
  • When you use new Function(…) (the Function constructor ) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
  • A closure in JavaScript is like keeping a reference ( NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
  • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
  • A new set of local variables is created every time a function is called.
  • Douglas Crockford's simulated private attributes and private methods for an object, using closures.
  • A great explanation of how closures can cause memory leaks in IE if you are not careful.
  • MDN documentation on JavaScript Closures .

Javascript – Remove properties from objects (JavaScript)

To remove a property from an object (mutating the object), you can do it like this:

For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete statement on their blog, Understanding delete . It is highly recommended.

If you'd like a new object with all the keys of the original except some, you could use the destructuring .

Related Question

  • Javascript – How to loop through or enumerate a JavaScript object
  • Javascript – the JavaScript version of sleep()
  • Javascript – Get the current URL with JavaScript
  • Javascript – Sort array of objects by string property value
  • Javascript – What does “use strict” do in JavaScript, and what is the reasoning behind it
  • Php – Reference — What does this symbol mean in PHP
  • Javascript – standard function to check for null, undefined, or blank variables in JavaScript
  • Javascript – How to return the response from an asynchronous call

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript variables, variables are containers for storing data.

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • Using const

In this first example, x , y , and z are undeclared variables.

They are automatically declared when first used:

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

Example using const, mixed example.

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

From the example above, you can guess that the total is calculated to be 11.

Variables are containers for storing values.

Advertisement

JavaScript Identifiers

All JavaScript variables must be identified with unique names .

These unique names are called identifiers .

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript identifiers are case-sensitive.

The Assignment Operator

In JavaScript, the equal sign ( = ) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

After the declaration, the variable has no value (technically it is undefined ).

To assign a value to the variable, use the equal sign:

You can also assign a value to the variable when you declare it:

In the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma :

A declaration can span multiple lines:

Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined .

The variable carName will have the value undefined after the execution of this statement:

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var , it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these statements:

You cannot re-declare a variable declared with let or const .

This will not work:

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :

You can also add strings, but strings will be concatenated:

Also try this:

If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Now try this:

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements".

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

Test Yourself With Exercises

Create a variable called carName and assign the value Volvo to it.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. How To Declare And Assign Values To Variables In JavaScript

    assign smarty variable in javascript

  2. Two Ways To Declare Variables In JavaScript

    assign smarty variable in javascript

  3. Javascript Variable (with Examples)

    assign smarty variable in javascript

  4. Values and Variables in JavaScript

    assign smarty variable in javascript

  5. JavaScript Variables

    assign smarty variable in javascript

  6. Learn Javascript, Create a Variable, codecademy, Javascript Tutorial

    assign smarty variable in javascript

VIDEO

  1. variable in javascript hindi

  2. Javascript Objects

  3. Variable Hosting in JavaScript |Day 18 #75hardchallenge #coding ##backend #javascript #nodejs

  4. JavaScript Tutorial in Urdu For beginners

  5. 01

  6. 18- Function Parameters In JavaScript up

COMMENTS

  1. how to assign a javascript variable to a smarty variable

    2 Answers Sorted by: 7 You can't assign a client-side value to a smarty variable, as smarty is a templating language that runs on the server. Smarty assignments can only be done on the server-side, that is to say, from PHP. E.g.: $smarty->assign ('timestamp',time ()); So what you can do is something like:

  2. php

    2 Answers Sorted by: 4 Smarty 2 requires escaping of the " {" and "}" characters, you can use {ldelim} and {rdelim} to escape them individually or wrap entire blocks of text with {literal} {/literal}.

  3. Assigning variables

    Using $smarty->assign () is the most common way of assigning data to templates, but there are several other methods. Appending data to an existing variable Using append (), you can add data to an existing variable, usually an array. If you append to a string value, it is converted to an array value and then appended to.

  4. Smarty :: View topic

    Code: var sample = {$smarty_variable}; Back to top erunways Smarty n00b Joined: 16 Nov 2009 Posts: 3 Posted: Fri Dec 04, 2009 10:57 pm Post subject: How to use SMARTY variables in JavaScript Here is the exact link to the example: http://erunways.com/how-to-use-smarty-variables-in-javascript/ Back to top scuzzy Smarty Regular Joined: 31 Aug 2003

  5. Smarty inside javascript condition ... possible?

    1 I am trying to have a javascript condition and mix it with smarty code...is this possible? For example: <script> if (myjsVar == '2') { {some smarty here} } </script> This is what I'm trying to do: {literal} <script type="text/javascript"> myjsVar = '2'; if (myjsVar == '2') { {include file='inc.html'} } </script> {/literal}

  6. Variables

    Variables | Smarty Variables Template variables start with the $dollar sign. They can contain numbers, letters and underscores, much like a PHP variable . You can reference arrays by index numerically or non-numerically. Also reference object properties and methods.

  7. {assign}

    {assign} is used for assigning template variables during the execution of a template . Note Assignment of variables in-template is essentially placing application logic into the presentation that may be better handled in PHP. Use at your own discretion. Note See also the short-form method of assigning template vars. Attributes: Option Flags:

  8. Smarty :: View topic

    <script type="text/javascript"> var newVar = " {$dynamicValue}"; </script> That said, it is possible that there are rogue characters in the smarty var that javascript may not like, so just escape them: Code: <script type="text/javascript"> var newVar = " {$dynamicValue|escape:javascript}"; </script>

  9. custom fields

    0. add {debug} into your template, it should show you all the variables that are assigned, if you are lucky, the variable you want is already there. If it isn't you need to write a bit of php code to assign it to the template. Depends on where/how you want it, but the more "future proof" is to create an extension (with civix) and use a hook ...

  10. Chapter 4. Variables

    Smarty has several different types of variables. The type of the variable depends on what symbol it is prefixed or enclosed within. Variables in Smarty can be either displayed directly or used as arguments for functions , attributes and modifiers, inside conditional expressions, etc.

  11. Smarty

    {else} {assign var="days_left" value="`$today`"} /* $days_left = today */ {/if} The key here is that when you want to include a variable as part of the value of another variable you need to use value="$in_days". Notice the ` before and after the variable name inside the double quotes.

  12. Smarty variables inside JS files

    The main problem I experienced is that you can read a perfectly fine JavaScript object as Smarty variable, due to the use of single { } as variable's delimiters. counter example from Twig, where ...

  13. {assign}

    Attribute Name Required Description; scope (optional) The scope of the assigned variable: \'parent\',\'root\' or \'global\'

  14. [Solved] assigning a javascript value to Smarty?

    Has anyone tried assigning a javascript variable's value to smarty using ajax or something similar? For example, if I need to test the browser's viewport width using JS, can I somehow assign the result (a number) to a Smarty var using an ajaxy request from a _GET or something?

  15. [SOLVED] Passing Smarty variable to javascript function

    [SOLVED] Passing Smarty variable to javascript function. Xlinesoft forums Toggle navigation. Menu All topics Advanced Search Notifications Login Blue. White. Purple. Green. Red. Orange. Blue Light. White Light. Purple Light. Green Light. Red Light. Orange Light. PHPRunner General questions

  16. Assign JavaScript variable to Smarty variable

    Javascript - Assign JavaScript variable to Smarty variable. javascript php smarty. This question already has answers here: Closed 10 years ago. Possible Duplicate: how to assign a javascript variable to a smarty variable. I want to assign a textfield value to Smarty variable using JavaScript and call Smarty function but I could not do it ...

  17. Smarty :: View topic

    Assign Smarty variable from Javascript variable Smarty Forum Index-> Feature Requests: View previous topic:: View next topic ... in console when the radio button is clicked, I have 'Ja' printed, but I want to pass it's value into smarty variable because I will send it as a parameter in php function. Is this possible and how I can do that? ...

  18. JavaScript Variables

    All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs.

  19. How to pass a smarty variable to a JS

    In js class I try to read it using. var ts = $('#expiry_date').text() or var ts = $('#expiry_date').val() In both text() and val() cases date is not retreived from html.