How can I check if a variable exists in Smarty?
Asked Answered
R

4

31

I'm using Smarty template engine.

I'm doing a simple login page. I set a variabile named error with a message if there are some problems, but IF NOT I get:

Notice: Undefined index: error

How could I check if this variable exists?

I only do:

{if $error}<h1>{$error}</h1>{/if}

thanks

Raw answered 13/10, 2011 at 9:15 Comment(1)
The answers below do not take into account that a variable can be set to null. $error may exist and be null, in which case isset($error) returns false.Dovetail
I
57

isset() - smarty - php

isset($error)
Insufflate answered 13/10, 2011 at 9:20 Comment(0)
M
68

There you go!

{if isset($error)}
    {* TODO something *}
{/if}
Microminiaturization answered 13/10, 2011 at 9:19 Comment(0)
I
57

isset() - smarty - php

isset($error)
Insufflate answered 13/10, 2011 at 9:20 Comment(0)
A
3

You can also use:

{if $error|default}<h1>{$error}</h1>{/if}

"|default" modifier check if variable exist and accept one param (default: empty string)

Archducal answered 6/11, 2021 at 0:12 Comment(0)
R
-3

This is short :) No warnings or errors.

{if $error}
Robbyrobbyn answered 17/3, 2018 at 12:32 Comment(2)
As you could see in the question this produces a notice. I assume you have the errorlevel high enough that you don't see notices.Rooted
In PHP 8.1, the notice has become a warning: PHP Warning: Attempt to read property "value" on null in [template]. The compiled code would here be <?php if ($_smarty_tpl->tpl_vars['error']->value) {?>, but tpl_vars['error'] wouldn't exist.Buffington

© 2022 - 2025 — McMap. All rights reserved.