2

How to I access a javascript template that is reused throughout my site, and do so within javascript and bind a object to it. I would like access to the template as a string so I can add it in the content property below in a Google Maps Info Window.

I know there's this function ko.renderTemplate("myTemplate", accessor, {}, element, 'replaceNode'); but how can I get that to return me the string to shoot to the info window?

<script type="text/html" id="info-window-test">

   <span data-bind="text: Name"></span>

</script>

   var html = TODO: Get Template With Data

  /***************** OLD WAY
    var html = '<div class="info-window">';

        html = html + '<div><b>' + location.City + ', ' + location.StateRegion + '</b></div><hr/>';

        length = location.Events.length;

        $.each(location.Events, function (index, item) {
            html = html + '<div><a target="_blank" href="' + item.Link + '">' + item.Name + '</a></div>';
            html = html + '<div><i>' + item.DateFormatted + '</i></div>';

            if (index < length - 1) {
                html = html + '<hr/>';
            }
        });

        html = html + '</div>';
    **************************/

    var infoWindow = new google.maps.InfoWindow({
       content: html
    });
2
  • Could you elaborate? I don't quite understand the problem. A fiddle would help Commented Jan 31, 2013 at 5:31
  • A fiddle would help if I knew an actual implementation. I want to do something like $.template('info-window-test', data) and return the string of it, but do it with knockout.js without referencing jquery templates to do so. Is that possible? Commented Jan 31, 2013 at 15:52

1 Answer 1

3

If I have understood your question correctly it should be "Can I use KnockoutJS as a simple template engine?" and the simple answer is No, you cannot.

But you can use the DOM temporally to achieve what you want.

Check this jsfiddle http://jsfiddle.net/angelyordanov/zQZT8/.

<script type="text/html" id="info-window-test">  
  <span data-bind="text: Name"></span>  
</script>  
var viewModel = { Name: 'John' };

var templatePlaceholder = 
  $('<div style="display: none" data-bind="template: { name: \'info-window-test\' }"></div>')
  .appendTo('body');

ko.applyBindings(viewModel, templatePlaceholder[0]);

var resultHtml = templatePlaceholder.html();

ko.cleanNode(templatePlaceholder[0]);
templatePlaceholder.remove();

alert(resultHtml);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.