wongadob Posted December 18, 2012 Share Posted December 18, 2012 Hi I am using templates in Knockout JS and I am trying to create conditional markup within the template. The code I have is as follows (bit does not work and I don't think it is possible to do it this way within a template (I think this is the method outside templates) So does anybody know how it can be done <script type='text/html' id="mainPageTemplate"> <!-- ko if: ($index()%2==0) --> <div class="row group"> <!-- /ko --> <div class='seriesFeature col'> <a class='sect-nav' data-nav='pi_family' data-bind="click:goFamily.bind($data,id)"> <h4 data-bind = "text: name"></h4> <img data-bind="attr: {src: image}"></a> <p data-bind="text: description"></p> </div> <!-- ko if: ($index()%2==0) --> </div> <!-- /ko --> </script> The HTML setup is as follows <div id="pi_mainPage" data-bind="template: {name: 'mainPageTemplate', foreach: productInfoMain.families}"></div> So for element 0,2,4,6,8...... I want it to add the containing div with classes row & group. Any help much appreciated as I an stumped. I did try using the CSS nth-child but with the element having multiple classes it got a bit messy and for clarify it should really be in the HTML. Link to comment Share on other sites More sharing options...
dsonesuk Posted December 18, 2012 Share Posted December 18, 2012 This works using jquery, but i can't guarantee if it will work for template system or cause problems for data-bind when cloning. $(function (){$('.seriesFeature:even').addClass("remove");$('.seriesFeature:even').before('<div class="row group"></div>')$('.remove').each(function(){ $(this).clone().appendTo($(this).prev('.row')); $(this).prev('.row').find('.remove').removeClass('remove');});$('.remove').remove();}); Link to comment Share on other sites More sharing options...
wongadob Posted December 19, 2012 Author Share Posted December 19, 2012 I can't believe there is no option for conditional operations within a template, surely there must be. I originally had the page creating itself into a string and then using appendTo, but the client wants it all to be using page templates for easy of future changes. I looked at using Jquery templates but I read that they were not supported anymore, particularly with Knockout JS. So I am trying to keep to pure Knockout js with mapping. Anyone else got any ideas? Thanks Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now