Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render container conditionally

Is it possible to render container for a template based on condition with knockout.js?

This does not work, but shows what i want to do:

<div data-bind="foreach: items">
 <!-- ko if: $data.startContainer -->
 <div class="container">
 <!-- ko -->

 <div data-bind="html: $data.contentElement"></div>

 <!-- ko if: $data.endContainer -->
 </div>
 <!-- ko -->
</div>
like image 538
Anri Avatar asked May 07 '13 18:05

Anri


People also ask

How do you conditional render in JavaScript?

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.

Should you use ternary or && operator to conditionally render React components?

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”.


1 Answers

Found a thread on knockout.js github site that indicates this as not possible with the native templating model: https://github.com/SteveSanderson/knockout/issues/307

Apparently, the closing comment is understand as internal to the not closed div tag.

My hopes were on the dynamic templates, but failed also like shown in the fiddle.

http://jsfiddle.net/XbdGs/3/

<script type="text/html" id="withContainer">
     <div class="container">
         <!-- ko template: 'withoutContainer' -->
         <!-- /ko -->
     </div>
</script>

From that i conclude you can try the 3 foreachs solution, use Posthuma suggestion or fallback to another templating engine like jquery.tmpl or Underscore as mentioned on knockout documentation.

http://knockoutjs.com/documentation/template-binding.html

like image 132
Ricardo Medeiros Penna Avatar answered Sep 22 '22 04:09

Ricardo Medeiros Penna