How to use switch case in Mustache template?

只谈情不闲聊 提交于 2019-12-10 20:23:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!