• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

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.

How to use assigned Smarty variables inside an if condition?

Basicaly I have a smarty variable called VAR, which, if it's value is '1', should include file number1, otherwise it should include file number2, but I can't seem to make it work.

I have two pages, a PHP page where I assign the variable, and another with the Smarty code:

When I echo $VAR in the PHP page, it shows 1, but when I go to the Smarty page, it always shows number2.tpl.

What am I doing wrong? Thank you so much for your time.

manuel mourato's user avatar

Your {if} statement lacks spacing. The correct syntax here should be:

The Smarty {if},{elseif},{else} documentation states:

The following is a list of recognized qualifiers, which must be separated from surrounding elements by spaces. Note that items listed in [brackets] are optional. PHP equivalents are shown where applicable.

Full documentation is available here:

http://www.smarty.net/docsv2/en/language.function.if.tpl

Colin Smillie's user avatar

Your Answer

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 , privacy policy and cookie policy

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

Hot Network Questions

smarty assign variable in if

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

in English German Spanish French Italian Japanese Portuguese Russian General Development

About Smarty

Smarty icon.

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

Smarty Template Engine

Sites Using Smarty

Advertisement.

assign() — assign variables/objects to the templates

Description

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.

When you assign/register objects to templates, be sure that all properties and methods accessed from the template are for presentation purposes only. It is very easy to inject application logic through objects, and this leads to poor designs that are difficult to manage. See the Best Practices section of the Smarty website.

Example 14.6. assign()

These are accessed in the template with

To access more complex array assignments see {foreach} and {section}

See also assignByRef() , getTemplateVars() , clearAssign() , append() and {assign}

Sponsors [info]

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

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

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:

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 *

WHMCS.Community

Forgot your password?

Error assign smarty variable

By adixm , October 15, 2020 in Troubleshooting Issues

Recommended Posts

Adixm    0.

I tried to assign a new variable in php. After upgrade to whmcs 8 $template->assign is not available anymore.  

Quote Error: Call to a member function assign() on null in

This is the code

Share this post

Link to post, share on other sites, whmcs john    242.

WHMCS John

Hi @adixm ,

Here are the relevant resources you'll need:

https://docs.whmcs.com/Version_8.0.0_Release_Notes#Library_Updates

https://developers.whmcs.com/advanced/upgrade-to-whmcs-8/

brian!    3432

brian!

21 hours ago, adixm said: I tried to assign a new variable in php.

if you're creating PHP pages and wanting to add variables in them, then the creating pages docs explains that you could use...

if you're using a hook, then you can just return the variable.

... and if you're in the Smarty template, you can assign a variable directly without any changes to the Smarty Security Policy - the shorthand way to do that would be...

though there is a longer method as outline in the Smarty docs.

heapmaster    1

On 10/16/2020 at 7:46 AM, brian! said: if you're creating PHP pages and wanting to add variables in them, then the creating pages docs explains that you could use... $services = "Testtt" ; $ca -> assign ( 'vari' , $services ); if you're using a hook, then you can just return the variable. ... and if you're in the Smarty template, you can assign a variable directly without any changes to the Smarty Security Policy - the shorthand way to do that would be... {assign vari "Testtt"} though there is a longer method as outline in the Smarty docs.

How do you do this in a hook?  For example in a hook file with ClientAreaPage, how do I change the companyname smarty variable before its used in the template in WHMCS v8+ ?

15 hours ago, heapmaster said: For example in a hook file with ClientAreaPage, how do I change the companyname smarty variable before its used in the template in WHMCS v8+ ?
11 hours ago, brian! said: <? php add_hook ( 'ClientAreaPage' , 1 , function ( $vars ) { $newcompanyname = "heapmaster" ; return array ( "companyname" => $newcompanyname ); });  

Ya thats what I have and its not working in 8.0.4, I raised a support ticket

10 hours ago, heapmaster said: Ya thats what I have and its not working in 8.0.4, I raised a support ticket

what exactly are you trying to do ?

the above hook would just change the company name variable used in the header - so the new variable text would be shown in Six (if there wasn't a valid logo) and also used in the page title...

ytVFu2E.png

the above image is from v8.0.4 🙂

1 hour ago, brian! said: what exactly are you trying to do ? the above hook would just change the company name variable used in the header - so the new variable text would be shown in Six (if there wasn't a valid logo) and also used in the page title... the above image is from v8.0.4 🙂

Im trying to change the logo URL at the top from the hook and the Copyright footer of company name and date in the footer template.

6 minutes ago, heapmaster said: Im trying to change the logo URL at the top from the hook and the Copyright footer of company name and date in the footer template.

well the above hook would change the companyname variable in the footer (assuming your footer uses that variable), and you would need to use JS on a hook to change the URL (or just edit the header.tpl template!).

35 minutes ago, brian! said: well the above hook would change the companyname variable in the footer (assuming your footer uses that variable), and you would need to use JS on a hook to change the URL (or just edit the header.tpl template!).

Thanks, ya in my dev install this works, all three are changed in the header and footer, but my live install it does not work and they are both 8.0.4 R1, so odd..still debugging..

function client_area_companyinfo_change_it($vars) { $aryReturnArrayData = array(); $aryReturnArrayData["companyname"] = "Test Company"; $aryReturnArrayData["date_year"] = "1234"; $aryReturnArrayData["assetLogoPath"] = "/images/logo.jpg"; return $aryReturnArrayData; } add_hook("ClientAreaPage",1,"client_area_companyinfo_change_it");

5 minutes ago, heapmaster said: Thanks, ya in my dev install this works, all three are changed in the header and footer, but my live install it does not work and they are both 8.0.4 R1, so odd..still debugging..

then assuming you haven't disabled hooking in the live site, is there any caching occurring, re cloudflare, litespeed etc... all else fails, clear the template cache and see if that helps.

2 minutes ago, brian! said: then assuming you haven't disabled hooking in the live site, is there any caching occurring, re cloudflare, litespeed etc... all else fails, clear the template cache and see if that helps.  

Hooking is working because I add exit; before the return and I get a blank page so the hook is being called. I cleared the template_c folder and we dont have litespeed or cloudflare and still it does not work....

with the same template in both live & dev installs ?

Yes, both installs are the six default html template not modified (we like to do all modifications in hooks files).

I think I figured it out, it was a hooks file in a addon that was overriding my hook. I would change it and then it would run and change it back.

I fixed it by doing add_hook("ClientAreaPage",300,"..... (changing the priority of my hook to be higher)

16 hours ago, heapmaster said: I fixed it by doing add_hook("ClientAreaPage",300,"..... (changing the priority of my hook to be higher)

technically, you've made the priority of your hook lower rather than higher - so your hook will effectively run later, e.g after the addon hook runs.

Thanks, now I'm having the issue after talking to the addon developer that my hook is overriding their hook. Similar to what is described here 

It seems variable changes made in the first hook do not get passed into the second hook and then to WHMCS. So its either one hook or the other and not both for some reason. WHMCS should pass the results of the changed variables to the second hook for processing, and then those changes of the variables from both hooks then passed to the template from WHMCS. But its not doing that.

This needs to be fixed internally within the WHMCS code...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest

×   Pasted as rich text.    Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.    Display as a link instead

×   Your previous content has been restored.    Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Recently Browsing    0 members

No registered users viewing this page.

Important Information

By using this site, you agree to our Terms of Use & Guidelines and understand your posts will initially be pre-moderated

DEV Community

DEV Community

dgloriaweb

Posted on Nov 25, 2021 • Updated on Sep 14, 2022

Php Smarty template - assigning complex content to variables

In some cases Smarty doesn't allow you to assign values to variables just like that. For example in foreach loops. Then the following solutions can work. 1, Assign a simple text with variables:

explanation: Smarty's smart enough to replace value of variable within quotes.

2, Assign special characters or longer text:

explanation: the capture tag allows you to add text without quotes so it's readable. Variables have to be in {}.

3, Do ternary operation and assign value:

explanation: need to be aware of the brackets, but works fine. Normal brackets contain the condition.

Ternary operator concatenate variables with string (if the parentname is set, concatenate variables to a new string)

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git

DRY principle could be harmful. Here's why.

Alex Pushkarev - Mar 3

blminami profile image

[Tailwind CSS] From CSS to Tailwind CSS

Narcisa - Mar 3

javierhf profile image

Improving Your Development Documentation Project (2 of 3)

Javier Hernández - Mar 3

gerardokaztro profile image

Cómo visualizar los hallazgos de Amazon GuardDuty en MS Teams

Gerardo Castro Arica - Mar 3

Once suspended, dgloriaweb will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, dgloriaweb will be able to comment and publish posts again.

Once unpublished, all posts by dgloriaweb will become hidden and only accessible to themselves.

If dgloriaweb is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to dgloriaweb.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag dgloriaweb:

dgloriaweb consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging dgloriaweb will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Stack Exchange Network

Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

CiviCRM Stack Exchange is a question and answer site for administrators and users of the CiviCRM Constituent Relationship Management software. It only takes a minute to sign up.

Q&A for work

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

If statement not working if the smarty variable is not set

I've been trying to figure this out for myself but I am super frustrated at this point! I've got smarty variables and conditional statements working in thank you letters. Well kind of working. Basically I'd like to include the contribution note if the note field is filled in, if it's not show the text "None". I can get the note to display but no matter what set up I've used I can't get it to show "None". I have two donations one with a note, one without. Here is what I've tried so far:

I've also tried capturing a smarty variable and then using it in the if statement.

Can anyone shed some light? (I'm sure a suggestion will be is to write some hook or custom token with this logic already worked in. But I'd really like to know why the if statement isn't working as straightforward as I'd imagined it would. I'd like to use more if statements for mailing labels etc and if I can't get an "else" to work that's a problem.)

(Wordpress 4.4.1 and Civi 4.6.4)

RayWright's user avatar

2 Answers 2

That's a good one, so if the contribution has no Note, no note record is created in the contribution table therefore the result is an empty array, I'm not sure of why none of your code is working, I believe is because the array is already initialized and smarty returns TRUE?

Workaround :

Let me know how that goes.

Andrei's user avatar

Paul-Tahoe's user avatar

Your Answer

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 , privacy policy and cookie policy

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

Hot Network Questions

smarty assign variable in if

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

PrestaShop Forums

Forgot your password?

Assigning variable to smarty

By mariusz_k , June 2, 2017 in Core developers

Recommended Posts

code added to product.tpl for display or not "add to cart" button

What I want to do now is to disable possibility "add to cart" for users from some countries.

Share this post

Link to post, share on other sites.

BalzoT

Hi there the common practice to do is to add the smarty variables in the controller of the page not in the class file

so you can keep the function to the Product.php but the smarty assign code should be moved to the ProductController.php inside the initContent function and changed to something like 

joseantgv

  I am trying to use sql query in php, assign the value result to smarty and then call it in .tpl file.   code added to product.php public function sendIdLangBySmarty($query_results) { $sql = 'SELECT id_country FROM '._DB_PREFIX_.'ps_adress WHERE id_customer = $cookie->id_customer'; $result = Db::getInstance()->getValue($sql); $this->context->smarty->assign('query_results', Db::getInstance()->getValue($result)); } code added to product.tpl for display or not "add to cart" button {if $is_logged && $query_results == 2} ..... {/if} What I want to do now is to disable possibility "add to cart" for users from some countries. I know this can be done easier. So why am i doing such a think? When this part will work correctly  I want to add another query to restrict this for only some products.   The question is what am I doing wrong? For now it's just doasn't working and i'am sure it's coused by php part becuse when I restrict only by $is_logged in .tpl it works like a charm.   I found some topics similar to my problem but still cannot do it correctly by myself.   

If you want to use a module...  https://addons.prestashop.com/en/order-management/26993-hide-price-and-disallow-purchase-of-products.html

;)

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.

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More

You are using an outdated browser. Please upgrade your browser to improve your experience.

Vanilla Forums

What's the easiest method to assign value from PHP to smarty?

warzyd

as in title, i am looking for the easiest way to assign the value from php to .tpl file in smarty. Already read several topics i found on this forum but none of them works.

And yes, I have created "class.mythemethemehooks.php" file in mian custom theme folder but seems like whatever i do in this file, does not affect default.master.tpl template.

Would be great if anyone can help.

Thanks in advance!

R_J

Something like

should be the solution

Bleistivt

Thanks @R_J . Should I locate functions for smarty in a specific file? If I will create the function as above, in .tpl should i use it like {someName} and that's it?

There is no single best solution. In the end it depends what you want to achieve. If we are talking about smarty functions, than please search the forum. I think I have started a discussion in the tutorial section about creating custom Smarty functions. But I would only do that a) if this is a complex function and b) it is used in multiple places on your page with different input. Otherwise I would suggest using the themehooks file.

But using base_render_before is not the best solution. Most of the time there are better events that you can hook into. If you give more details, I'll might be able to give better advice.

I have never done that much with Smarty, but this is simple enough to simply try it out ;-)

By the way: if you create a theme and afterwards add a themehooks file, you need to clear /cache/themes and if you change the default.master.tpl, it doesn't hurt to clear the /cache/smarty folder, too.

@R_J What I would like to do is basically pass some variables or function results to smarty so i can use it in .tpl files. That's all i would like to use. I did created theme hooks file according to your suggestion in other topic and the file is located in main folder of theme and its name is: class.MyThemeNamethemehooks.php

Inside this file, i have the following code:

but unfortunately, it does not work. When I try to use {someName} in default.master.tpl it simply does nothing. Thus, I wonder what i do wrong exactly.

Please search some more discussions on this. There has been a change how plugin folders must be added. I'm on mobile so I leave the searching part to you, sorry

I know that topic, this is where from i get above content ;) You refer to https://open.vanillaforums.com/discussion/27767/how-to-create-custom-smarty-functions

But my question is, if it is possible to pass just simple variables from functions located in class.MyThemeNamethemehooks.php file without moving each function to separate file in /SmartyPlugins/ folder ;)

This is the comment that you should look at:

Which page do you want to change or even better: which part of the interface do you want to inject values? As I said before: with base_render_before and setData you should be able to inject values to the default.master.tpl

But a) using base_render_before for all purposes is waste of resources and b) changing default.master.tpl is rarely needed

Normally you just intercept the view file and inject code via the hooks

Do you know any tutorial where i can find necessary details about that?

Well, documentation sucks. It became even worse since Vanilla uses its own Knowledge Base: the current developers documentation states it is incompletes and references to an old version but that is just a link to that same site:

The closest thing is here:

Taking a look at the existing plugins can also be very helpful:

But you can always ask questions here. Start by giving one detailed example of what you want to achieve (like e.g. adding post count below user name in discussions and comments), maybe with a screenshot and we will try to give you the code (that would need to be injected in the themehooks file

Thanks for the links. Been trying to work on it but it does not assign variables from MyThemeThemeHooks class/file to smart. Later read the following https://success.vanillaforums.com/kb/articles/233-smarty-overview#accessing-controller-data-with-smarty and as it explained here, I should be able to display available smarty vars by simply pasting {debug_vars} into default.master.tpl file. Even this, does not work. All I get, you can see on the screenshot below.

Screenshot at Nov 10 17-23-36.png

The file class.MySiteThemeHooks.php looks as below:

Screenshot at Nov 10 17-26-39.png

But in default.master.tpl i just tried to call {debug_vars} :

Screenshot at Nov 10 17-28-58.png

It's only {debug}

You're right, it does work now ;)

But why my custom value does not work? I mean {someName} in above example. It does display same error as above when used {debug_vars}

I was wrong with that base_render_before thing. Try this:

You would print it out with {$Hello}

Did tried above function instead and still does not work but seems to be closer to the final result. However, this time got different notice Undefined index: Hello and Trying to get property 'value' of non-object

Screenshot at Nov 10 19-20-15.png

Have you also seen my second comment? This is what I get:

grafik.png

Yes, did exactly as you described.

After further investigation, I noticed that the problem is with theme hooks file itself. I did everything according to https://success.vanillaforums.com/kb/articles/246-theme-hooks but seems like this file is not being taken into account.

First of all: if you create a theme which has no themehooks file and add that file later, you need to delete the content of /cache/themes.

Try to omit the dashes in the file and the class name: "OpenVfComThemeHooks" (delete the cache/themes folder after renaming class or file name).

If that doesn't work add the following line to your addon.json: "className": "OpenVfComThemeHooks", and don't forget to delete the /cache/themes folder afterwards ;-)

Thanks @R_J , you are the best ;) Removing the dashes in the file and class name, and later clearing cache/themes/ folder did the trick. Seems like cache was the main reason. Had no idea about that 🙈

easteregg

Sorry in advance for "hijacking" this thread - but I have the same question and following your steps in Version 2021.009 didn't work out for me.

So here is where I am at:

So what do I want to achieve: Simply having the {$Hello} variable available in Smarty, ideally with my test value "World". Every time I've emptied the /cache/theme/ folder.

Here my unsuccessful attempts at figuring it out via the MyThemeThemeHooks.php:

#3 (here you can see I became creative)

I've also checked the mytheme.php, which gets created in the cache folder - and it references the MyThemeThemeHooks...

Basically I had reached the point, where I had disbelief in my default.master.tpl - maybe I was missing a hook, or such. So I wanted to check another theme, Keystone: Since there also setData is used, I simply added a {debug_vars} to the template - and to my surprise, also there the custom setData didn't end up in Smarty.

Long story short: Any ideas what I did wrong?

The last 3 days I did stare at my code, but I am out of ideas. Maybe simply the sender-function is deprecated now?

Thanks in advance for any ideas

IMAGES

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

    smarty assign variable in if

  2. assign in smarty

    smarty assign variable in if

  3. 37 Smarty Variable In Javascript

    smarty assign variable in if

  4. เท ม เพ ร ต

    smarty assign variable in if

  5. 36 Smarty Variable In Javascript

    smarty assign variable in if

  6. 37 Smarty Variable In Javascript

    smarty assign variable in if

VIDEO

  1. Some More Functions

  2. Nested if statements 3 no gt .....☆☆☆▪︎▪︎▪︎¤¤¤••••☆☆☆•••☆

  3. Merging Data using DO-IF-ELSE LOOP SPSS Syntax

  4. If-Else Examples and Setup

  5. Data Analysis 101: Excel IF, IFS AND IF/OR FUNCTIONS

  6. What is a Variable?

COMMENTS

  1. How to use assigned Smarty variables inside an if condition?

    Try wrapping the 1 in quotes. if $VAR=="1" · What does {$VAR} output in Smarty? – Manmaru · @PanamaJack thank you! I'll try that now · @Manmaru

  2. assign

    {assign} is used for assigning template variables during the execution of a template. Note. Assignment of variables in-template is essentially

  3. assign()

    void assign(mixed var); void assign(string varname, mixed var,

  4. Smarty

    assign · ="num_days" value · "0" ; if $num_days != "0" ; assign · ="days_left" value · "`$in_days` `$days_until_expiry` `$days`"

  5. Smarty Cheat Sheet for Template Designers

    Smarty Cheat Sheet for Template Designers ... Assigning Variables. General Format ... {/if}. Logic. Smarty website : http://smarty.php.net.

  6. Error assign smarty variable

    if you're using a hook, then you can just return the variable. ... and if you're in the Smarty template, you can assign a variable directly

  7. Php Smarty template

    In some cases Smarty doesn't allow you to assign values to variables just like that. For example in foreach loops. Then the following solutions

  8. If statement not working if the smarty variable is not set

    I've also tried capturing a smarty variable and then using it in the if statement. {capture assign='note_text'}None{/capture} {if !$note.note}{$

  9. Assigning variable to smarty

    by php part becuse when I restrict only by $is_logged in .tpl it works like a charm. I found some topics similar to my problem but still cannot

  10. What's the easiest method to assign value from PHP to smarty?

    There is no single best solution. In the end it depends what you want to achieve. If we are talking about smarty functions, than please search