问题
I'm using Mustache template in Core PHP to turn PHP pages to template. Now I want to use switch case in template like:
<?php
switch ($gift_card['FlagStatus']) {
case 'P':
echo "Pending";
break;
case 'A':
echo "Active";
break;
case 'I':
echo "Inactive";
break;
}
?>
what should be its similar Mustache translation? thanks in advance
回答1:
If you need to do more than just output a single value from the switch statement, the simplest workaround is to create a series of booleans, one for each state: isPending
, isInactive
, isActive
etc and then use separate sections for each eventuality:
{{#isPending}}
Your gift card is pending. It will be activated on {{activationDate}}.
{{/isPending}}
{{#isActive}}
Your gift card is active. Its balance is ${{balance}}.
{{/isActive}}
{{#isInactive}}
Your gift card is inactive. Go <a href="/active/{{cardId}}">here</a> to reactivate it.
{{/isInactive}}
回答2:
The switch statement would go in the php, for example:
In the php
$card_status = null;
switch ($gift_card['FlagStatus']) {
case 'P':
$card_status = "Pending";
break;
case 'A':
$card_status = "Active";
break;
case 'I':
$card_status = "Inactive";
break;
}
render_template('giftcard_stuff', array('card_status'=>$card_status);
In the template
<div>The status of this gift card is: {{card_status}}</div>
Things get more tricky when you're trying to do things like put flags like that into a dropdown, in which case you'd have to write out the array in advance, like:
$status_dropdown = [
['flag_display'=>'Pending', 'flag'=>'P'],
['flag_display'=>'Active', 'flag'=>'A'],
['flag_display'=>'Inactive', 'flag'=>'I'],
];
来源:https://stackoverflow.com/questions/12158715/how-to-use-switch-case-in-mustache-template