|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
bimal Smarty Elite
Joined: 19 Apr 2007 Posts: 423
|
Posted: Tue Oct 05, 2010 12:26 pm Post subject: Ternary Operator within the template |
|
|
Requirements of ternary operators within a Smarty template is too less.
I just wanted to decode Y for "Yes", and N for "No".
It can be done easily with {if}..{else}..{/if}.
I came here with a comparison first, and sending the true/false flag to the operator. But the compiled PHP output is not good as I expected.
Code: | {{'N'==$member.is_admin}|ternary:'Yes':'No'} |
The above code uses ob_start(), ... buffers in its compiled PHP code.
So, I thought of passing all the values to the operator and print the codes.
Code: | {$member.is_admin|ternary:'Y':'Yes':'No'} |
By the way, this kind of modifier was already written in around 2007. You may check these URLs as well.
http://www.ninjacipher.com/2007/11/24/smarty-ternary-modifier/
http://www.smarty.net/forums/viewtopic.php?t=14622&highlight=ternary
http://www.smarty.net/forums/viewtopic.php?t=2044&highlight=ternary
http://www.smarty.net/forums/viewtopic.php?p=54700
The modifier plugin file (modifier.ternary.php) would look like:
Code: |
<?php
/**
* Ternary Operator in Smarty Templates
* @param $flag Boolean Input true or false as a value is compared within the template
* @param $yes_value String Print this value when the comparision is true
* @param $no_value String Print this value when the comparision is NOT true.
*/
function smarty_modifier_ternary($original_value='', $compare_to_value='', $yes_value='', $no_value='')
{
return ($original_value==$compare_to_value)?$yes_value:$no_value;
}
?>
|
|
|
Back to top |
|
U.Tews Administrator
Joined: 22 Nov 2006 Posts: 5068 Location: Hamburg / Germany
|
Posted: Wed Oct 06, 2010 9:04 pm Post subject: |
|
|
Smarty 3 does support ternary syntax
Code: | {('N'==$member.is_admin)?'Yes':'No'} |
|
|
Back to top |
|
Traumflug Smarty n00b
Joined: 16 Jun 2019 Posts: 1
|
Posted: Sun Jun 16, 2019 5:56 pm Post subject: |
|
|
U.Tews wrote: | Code: | {('N'==$member.is_admin)?'Yes':'No'} |
|
... nine years later ...
Secret here are these parentheses around the conditional. They're needed even for functions and methods. This doesn't work:
Code: | {ImageManager::retinaSupport() ? '2x' : ''} |
This works just fine:
Code: | {(ImageManager::retinaSupport()) ? '2x' : ''} |
|
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|