Magento 2 – Use getTemplate() Within KnockoutJS Foreach

knockoutjsmagento2

I get the following error when I try to use getTemplate() within KnockoutJS foreach.

Message: Unable to process binding "with: function(){return
getChild('my-child') }" Message: getChild is not defined. getChild is
not defined

This is how my KOjs template looks…

<!-- ko foreach: myObj -->
<div>some markup...</div>
    <!-- ko with: getChild('my-child') -->
        <!-- ko template: getTemplate() --><!-- /ko -->
    <!--/ko-->
<!--/ko-->

I'm able to render the template outside of the foreach.

I've tried using $parent.getChild but this does not work.

I've also tried this with the more common getRegion method below, but without success:

<!-- ko foreach: getRegion('my-child-area') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->

Best Answer

Actually using the $parent context property worked fine. I also had a extra space typo in my child template file name, which I had missed when I first tried using $parent

<!-- ko foreach: myObj -->
<div>some markup...</div>
    <!-- ko with: $parent.getChild('my-child') -->
        <!-- ko template: getTemplate() --><!-- /ko -->
    <!--/ko-->
<!--/ko-->
Related Topic