How to template If-Else structures in data-bound views?

后端 未结 4 961
陌清茗
陌清茗 2020-12-12 20:01

I constantly find myself using this idiom in KO-based HTML templates:




        
4条回答
  •  独厮守ぢ
    2020-12-12 20:32

    There are a couple different ways that you can handle this type of code.

    • with an if/ifnot combination like you are now. This works fine and is not terribly verbose.

    • Michael Best's switch/case binding (https://github.com/mbest/knockout-switch-case) is quite flexible and can let you easily handle this and more complicated ones (more states than true/false).

    • Another option is to use dynamic templates. You would bind an area to one or more templates with the template name being used based on an observable. Here is a post that I wrote on this topic a while back: http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html. In your scenario, it might look like:

    
    
    
    
    
    

    The getCellTemplate function could live wherever, but would be given the item ($data) as the first argument and would return the name of the template to use.

提交回复
热议问题