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).

assign var="num_days" value="0"} if $num_days != "0"} {assign var="days_left" value="`$in_days` `$days_until_expiry` `$days`"} /* $days_left = in 3 days */ 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. 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 *

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to assign global scope variables #194

@machavity

machavity commented Feb 23, 2016

I'm running the latest from the repo pull and have run across a problem. It manifested itself in being unable to pull in a subtemplate. What was odd is that the path, which relies on an assigned global variable, was being assigned in another previous subtemplate. This assignment works fine in 3.1.17 but appears to no longer work in the current version of Smarty


(called after Template 1)

Produces

If I assign it in each template it works... but this defeats the purpose

@uwetews

uwetews commented Feb 23, 2016

" value="$shareddir/Views/Product" scope="global" bubble_up}

for now,
but it will be reworked during the next couple of days for BC

read NEW_FEATURES.txt

Sorry, something went wrong.

Using global scopes is always dangerous as you may loose overview in complex template structures.

In your case the safest solution is

" value="$shareddir/Views/Product" scope="parent"}

It will assign the variable just in the calling template, so that it's know when Sub Template 2 is called.

All other variable scopes are not touched.

@uwetews

uwetews commented Mar 9, 2016

The fix is now in the master branch.

read the NEW_FEATURES.txt for details

No branches or pull requests

@machavity

  • Escaping Smarty parsing
  • Config Files
  • Debugging Console
  • Template inheritance
  • Template resources

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.

Config file variables are an exception to the \$dollar syntax and are instead referenced with surrounding #hashmarks#, or via the $smarty.config variable.

Note Although Smarty can handle some very complex expressions and syntax, it is a good rule of thumb to keep the template syntax minimal and focused on presentation. If you find your template syntax getting too complex, it may be a good idea to move the bits that do not deal explicitly with presentation to PHP by way of plugins or modifiers.

Request variables such as $_GET , $_SESSION , etc are available via the reserved $smarty variable.

See also $smarty , config variables {assign} and assign() .

PrestaShop Forums

  • Remember me Not recommended on shared computers

Forgot your password?

  • Core developers

advertisement_alt

Global Smarty Variables used in Prestashop

uddhava

By uddhava June 1, 2010 in Core developers

Recommended Posts

  • Popular Post

On my search for the GLOBALS Smarty variables in Prestashop i stumbled upon this gem :

Like

Link to comment

Share on other sites.

:)

  • 2 weeks later...

brandonc503

could you tell me where $base_dir is set at so that i can change all http: to https: thanks

Most variables get set by the config files in the /config folder

These are all set in /init.php

  • 11 months later...
Thx for the info. But the list seems to be a bit outdated. logged is deprecated, is there any substitute for this? TIA
  • 1 month later...

Talking of this subject, what about the order note comment field from checkout? In the PrestaShop 1.4.2.5 release it cheekily appears as a global Smarty $oldMessage on the page where you enter the note, and then.. it is gone when you click Next! (On the page after that in checkout the gift wrap message is put into $cart>-gift_message .. But where is the order note?!)

49818_VkaCqBNm1feLFD94wTAx_t

  • 4 months later...
Up to date globals are listed on: http://doc.prestashop.com/display/PS14/Creating+a+PrestaShop+module

I have a solution to find the current page.

{assign var='pageName' value=$smarty.server.PHP_SELF}

{$pageName}

the variable 'pageName' print its name with absolute path. then you need to subtr it.

Can i create a global variable in a module ?

I want to use this variable in every tpl file in my theme.

  • 1 year later...

MyWebsiteSpot

MyWebsiteSpot

On my search for the GLOBALS Smarty variables in Prestashop i stumbled upon this gem : ( Thx to Matt : http://www.sandfight...shop-uncovered/ )   01 $base_dir { root folder of your shop } 02 $base_dir_ssl { root folder of your shop using HTTPS protocol } 03 $content_dir { root folder of your shop depending on the SSL settings } 04 $img_ps_dir { root folder containing images "/img/" } 05 $img_dir { images folder in your current theme directory } 06 $css_dir { css folder inside the current theme folder } 07 $js_dir { JavaScript inside the theme folder } 08 $tpl_dir { theme root folder } 09 $modules_dir { modules root folder } 10 $mail_dir { mail templates root folder } 11 $lang_iso { current language ISO code } 12 $come_from { previous page address [absolute] } 13 $shop_name { your specified shop name } 14 $cart_qties { total number of products in the cart } 15 $cart { shopping cart contents } 16 $currencies { pulls available currencies } 17 $id_currency_cookie { selected currency id [cookie dependent] } 18 $currency { active currency } 19 $cookie { active cookie } 20 $languages { grabs available languages } 21 $logged { checks whether users is logged in } 22 $page_name { current page's name } 23 $customerName { customer name [session dependent] } 24 $priceDisplay { current price display settings [currency dependent] }   I have no idea if these are all working. I was looking for a global variable that has the URL of the current page. Anybody knows that ?

Thanks for the list... I have also found out that $module_name works in v1.4.9.0 and im using it in my template to add an active class to the navigation like so...

@MyWebsiteSpot

vekia

well, it's a bit old thread with not all global variables used in 1.5.x version
  • 5 months later...

rethus

How did Prestashop got the URL for the Media-Server (ccc) ? 

Some Modules seems not to implement the right Smarty-Variable for that.

For example Homeslider & advertising_block & Product-Highlight on startpage still use default-domainname for the images.

And is there a place to find all the current global variables used in 1.5 but mostly important in 1.6?

year ago i create smarty global variable list for prestashop 1.5

you can use all of them in prestashop 1.6

Appwards

Thanks Vekia, but that list contains {$base_dir} which does not work under 1.6

I've found this to be the solution:

__PS_BASE_URI__ is a constant defined in prestashop and those can be access through Smarty's {$smarty.const...} tag.

So, use {$smarty.const.__PS_BASE_URI__} en voilá.

GoFenice

please go through  http://blog.gofenice.com/prestashop/global-smarty-variables-used-in-prestashop/  for a list available smarty variables in prestashop.

  • 3 months later...

you should be able to accomplish your task/goal by going to backoffice preferences/general and setting "Force the SSL on all pages" to YES

  • 7 months later...

creation-handicap

creation-handicap

is there a way i can get the search value? as in  http://www.creation-handicap.ch/shop/suche?tag=Weihnachtskarten i want to get the value "weihnachten"

i got it! it's 

for searching for tags and

for default searching

Well... I sure cannot find global smarty variables at that link - am I missing something?

rocky

  • 2 years later...

[email protected]

On 4/25/2019 at 9:36 AM, [email protected] said: Can any one can say how can i active link on top horizontal menu in internal pages.   Suppose about us in there are two cms pages but i want about us remain active when click on internal pages of about. please give any solution. Thanks  Sumant kumar

how can i get url of - Road to the category

image.png

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Already have an account? Sign in here.

  • Existing user? Sign In
  • Online Users
  • Leaderboard
  • Code of Conduct
  • All Activity
  • Go back to prestashop.com
  • Project on GitHub
  • Addons Marketplace
  • Create New...

Smarty Home What is Smarty? Why use it? Use Cases and Work Flow Syntax Comparison Template Inheritance Best Practices Crash Course

Resources Download Quick Install Documentation Discussion Mailing Lists Github Example App

Links www.php.net www.phpinsider.com

Smarty Icon

You may use the Smarty logo according to the trademark notice .

Smarty Template Engine

Sites Using Smarty

Advertisement, search results for "forums".

  • inforesources ...list can be viewed at here Forums are at http://www.smarty.net/forums/ The wiki ...
  • preface ...find some help here in the forums and documentation. Other Template Engines Smar...
  • api.fetch ...e}' so you can post in our forums . {$login_url} List master {textformat wrap=40}...

Sponsors [info]

Smarty Copyright © 2002 – 2024 New Digital Group, Inc. All rights reserved.

This page generated in 0.00336 secs with TinyMVC and Smarty 3.

  • Todays topics

CodeIgniter Forums

Welcome Guest, Not a member yet?  






  •   Share on Google
  •   Share on Facebook
  •   Share on Twitter
  •   View a Printable Version
  •   Subscribe to this thread
  •   Add Poll to this thread
  •   Send thread to a friend
  •   Linear Mode
  •   Threaded Mode
11-21-2012, 04:00 AM



I was wondering what is the equivalent of the code above Smarty. Cause $this->smarty->assign("places", $list_places); does not create global variables!



Thank you 11-23-2012, 08:05 PM


If you want to see a way of integrating Smarty but keeping CI-style code (aka $this->load->view()), see my Github Repo:
  • RSS Syndication

CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Get smarty variable into JavaScript

I want to make a simple snippet. I would like to console.log a smarty variable. I tried :

And in my JavaScript

It give me a blank page and nothing in the console log. In log I get

Smarty Error: Syntax error in template "file:/usr/share/nginx/html/page.tpl" on line 367 "{/literal}{$smarty.lbrace}{literal}" $smarty.lbrace is not defined

I also tried

It output {$somevar}

console.log return blank

executable's user avatar

  • The second won't work because it's considering {$somevar} as a literal too, that's why you need to stop the literal and restart it. The first one not working is weird tho. Could you add the full hierarchy and if you have anything else in your file? –  Alexandre Elshobokshy Commented Feb 20, 2019 at 13:03
  • This code is in the same file. I'm using it on whmcs –  executable Commented Feb 20, 2019 at 13:04
  • 1 I fixed, it was a typo error, sorry about that ! But I still cannot log new_var –  executable Commented Feb 20, 2019 at 13:09
  • If you try to console.log("string test") does it show the result? –  Alexandre Elshobokshy Commented Feb 20, 2019 at 13:09
  • @Islam Yes I can output in console.log. It look like the new_var is empty but I don't know why –  executable Commented Feb 20, 2019 at 13:10

First of all, declare your smarty variable :

And, use it in your .tpl file who will contains your JavaScript in < script> tag :

if you want to use a value from the PHP, you assign it to the smarty object, call the view, and display it with the same method.

Fizik26's user avatar

  • He's not looking to assign a smarty object, he's looking to use a PHP assigned variable inside smarty. I'm not sure you really understood the question. –  Alexandre Elshobokshy Commented Feb 20, 2019 at 15:14

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged php smarty or ask your own question .

  • The Overflow Blog
  • The framework helping devs build LLM apps
  • How to bridge the gap between Web2 skills and Web3 workflows
  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Infinite output impedance in amplifier, instead of 0?
  • Why are there two cables connected to this GFCI outlet?
  • Where does the energy in a fundamental interaction come from?
  • What make and model of aircraft is this?
  • When can widening conversions cause problems?
  • How do I know if a motion is 1 dimensional or 2 dimensional?
  • What is the name of the floor pump part that depresses the valve stem?
  • A story about a personal mode of teleportation, called "jaunting," possibly in Analog or Amazing Stories
  • Can a web-service based on AGPL 3.0 Licensed software demand money for its services?
  • How to receive large files guaranteeing authenticity, integrity and sending time
  • The Zentralblatt asked me to review a worthless paper, what to do?
  • Can your boss take vouchers from you, offered from suppliers?
  • What goods yield the best profit for time-travel arbitrage?
  • How to request for a package to be added to the Fedora repositories?
  • What concretely does it mean to "do mathematics in a topos X"?
  • Why not use computers to evaluate strength of players?
  • What is the meaning of the "Super 8 - Interactive Teaser" under "EXTRAS" in Portal 2?
  • I can't find a nice literal translation for "Stella caelis exstirpavit"
  • What are good reasons for declining to referee a manuscript that hasn't been posted on arXiv?
  • Is "Ἐλλάχ" the proper Greek transliteration of "Allah"?
  • Would human-shaped sperm cells work?
  • replacing a 15-amp breaker with a 20-amp breaker
  • Why can THHN/THWN go in Schedule 40 PVC but NM cable (Romex) requires Schedule 80?
  • Left crank arm misaligned on climb

smarty assign global variable

IMAGES

  1. 🎉 Smarty assign variable. Smarty assign variables. 2019-02-01

    smarty assign global variable

  2. 🎉 Smarty assign variable. Smarty assign variables. 2019-02-01

    smarty assign global variable

  3. Global Variable in Python

    smarty assign global variable

  4. [Solved] Smarty: check if variable is in array

    smarty assign global variable

  5. Python Global Variable

    smarty assign global variable

  6. GIS: Assign global variable to field in related table

    smarty assign global variable

VIDEO

  1. FreeFire Live Top 1 Global Player New Push Season Day3 #srvbiraj #freefirelive #rank pusH

  2. FreeFire Live Top 1 Global Player New Push Season Day2 #srvbiraj #freefirelive #rank pusH

  3. Yes Smarty Pie vs ujjwal #shorts #minecraft

  4. Summer vacation project By shubh Shree Ram global school Topper kid Cp1

  5. fish Smarty #music #funny #trending #fishing#love#safar #taubatauba #hindisong #newsong

  6. Advance Analysis PSpice Monte Carlo Analysis

COMMENTS

  1. {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.

  2. Add a new global variable in smarty? available on all pages

    How to set a Smarty Variable. In case you want to set a smarty variable you will have first to assign it. You can do it through a module, controller or a TPL. From a module or a controller it will be available as soon as you declare it. To print or to debug it.

  3. Assigning variables

    Assigning to template objects. When you use a template objects, as explained in rendering a template, you can assign data to the template objects directly instead of assigning it to Smarty. This way, you can use different sets of data for different templates.

  4. Variables

    You may use the Smarty logo according to the trademark notice.. For sponsorship, advertising, news or other inquiries, contact us at:

  5. {assign}

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

  6. assign()

    void assign (string varname, mixed var, bool nocache); You can explicitly pass name/value pairs, or associative arrays containing the name/value pairs. If you pass the optional third nocache parameter of TRUE, the variable is assigned as nocache variable. See Cacheability of Variables for details.

  7. Variables

    Although Smarty can handle some very complex expressions and syntax, it is a good rule of thumb to keep the template syntax minimal and focused on presentation. If you find your template syntax getting too complex, it may be a good idea to move the bits that do not deal explicitly with presentation to PHP by way of plugins or modifiers.

  8. Add new global smarty variable

    Hi, I would like to know how I can add a variable in every smarty template. For example, we can use {$urls.base_url} because $urls is an array that has been assigned ...

  9. Variable scopes

    Variable scopes. You have the choice to assign variables to the scope of the main Smarty object, data objects created with createData () , and template objects created with createTemplate (). These objects can be chained. A template sees all the variables of its own object and all variables assigned to the objects in its chain of parent objects.

  10. Smarty

    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 ...

  11. Unable to assign global scope variables · Issue #194 · smarty-php

    Unable to assign global scope variables #194. Closed machavity opened this issue Feb 23, 2016 · 3 comments ... which relies on an assigned global variable, was being assigned in another previous subtemplate. ... This assignment works fine in 3.1.17 but appears to no longer work in the current version of Smarty. SubTemplate 1 {assign var ...

  12. Prestashop 1.7: Smarty global variables

    Prestashop Tutorials. /. Prestashop 1.7: Smarty global variables. Image: People vector created by freepik - www.freepik.com. When developing your ecommerce site, you may need to view an item based on a condition or not. To do that, you need to edit the theme files using some Smarty language variables used by Prestashop.

  13. {$smarty} reserved variable

    Although Smarty provides direct access to PHP super globals for convenience, it should be used with caution. Directly accessing super globals mixes underlying application code structure with templates. A good practice is to assign specific needed values to template vars.

  14. Variables

    Although Smarty can handle some very complex expressions and syntax, it is a good rule of thumb to keep the template syntax minimal and focused on presentation. If you find your template syntax getting too complex, it may be a good idea to move the bits that do not deal explicitly with presentation to PHP by way of plugins or modifiers.

  15. Global Smarty Variables used in Prestashop

    Some Modules seems not to implement the right Smarty-Variable for that. For example Homeslider & advertising_block & Product-Highlight on startpage still use default-domainname for the images. Link to comment

  16. Smarty :: View topic

    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.

  17. Smarty: Assigning global variable from controller

    CodeIgniter Forums Archived Discussions Archived Development & Programming Smarty: Assigning global variable from controller

  18. How to make a variable globally accessible in Prestashop

    Then, you need to assign this php variable to a Smarty variable to show the value in the tpl file. To do this we use the method used by "@Ravinder Pal" but changing the value: ... Where define new global variable in Prestashop. 1. Initialize a constant variable in PS_CONFIGURATION. 0. Global JS variable in Prestashop 1.6. 1. SMARTY: Variable ...

  19. php

    1. First of all, declare your smarty variable : And, use it in your .tpl file who will contains your JavaScript in < script> tag : if you want to use a value from the PHP, you assign it to the smarty object, call the view, and display it with the same method.