7

I got a problem with Smarty and constants. I got three constant especified in a file:

DEFINE('ARTICLE_COLOUR_10', 'Light green');
DEFINE('ARTICLE_COLOUR_11', 'Claret'); // Bordó
DEFINE('ARTICLE_COLOUR_12', 'Yellow');

In DB I save only the numbers (10, 11, 12) and I send those numbers through this var

$sql_query_int = mysqli_query($connectdb, "SELECT colour FROM stock WHERE product='$articleId'");    
$smarty->assign('colours', $sql_query_int);

In TPL I get those numbers

{foreach from=$colours key=field item=value}
    {$value.colour}<br>
{/foreach}

Now I want to get the variable ARTICLE_COLOUR_$value.colour; I tried with three different ways but I couldn't get the complete variable.

{$smarty.const.ARTICLE_COLOUR_{$value.colour}}
{$smarty.const.ARTICLE_COLOUR_$value.colour}
{$smarty.const.ARTICLE_COLOUR_value.colour}

Fatal error: Smarty error: [in C:\xampp\htdocs/templates/default/tpl\article.tpl line 10]: syntax error: $smarty.$value.colour is an invalid reference (Smarty_Compiler.class.php, line 2169) in C:\xampp\htdocs\inc\smarty\Smarty.class.php on line 1109

I will be grateful for your help with this problem and forgiveness if this question is misspelled, my English is not very advanced.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Marcos Muñoz
  • 73
  • 1
  • 4

4 Answers4

6
{constant("ARTICLE_COLOUR_{$value.colour}")}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
3

If you want to get the value of a class constant in a smarty template you can use php constant() function.

<?php

namespace \MyNamespace;

class MyClass
{
    const FOO = "Bar";
}

In the template file:

{constant('\MyNamespace\MyClass::FOO')}

and this outputs the value of the constant.

Pavel Petrov
  • 847
  • 10
  • 19
0

maybe you can try $colours|@var_dump check $value.colour is assigned.

or try assign colours array

{assign var='colours' value=','|explode:"10,11,12"}
Dkstu.Tw
  • 82
  • 1
  • 4
0

There's a way that will probably work (in Smarty 3 at least), but involves calling get_defined_constants from smarty:

{$sysconst=get_defined_constants()}
{$articlevar='ARTICLE_COLOUR_'|cat:$value.colour}

{$sysconst.$articlevar}

This is kind of a hack, though... the proper way to do what you want would be to use regular arrays or variables instead of constants and assign them to smarty the usual way

Borgtex
  • 3,235
  • 1
  • 19
  • 28