tildeio / htmlbars

A variant of Handlebars that emits DOM and allows you to write helpers that manipulate live DOM nodes
MIT License
1.6k stars 193 forks source link

[Question] How to make HtmlBars render a template into existing DOM structure? #372

Closed OrKoN closed 9 years ago

OrKoN commented 9 years ago

I have the following code (based on the demo):

      var compiler    = requireModule('htmlbars-compiler'),
          DOMHelper   = requireModule('dom-helper').default,
          hooks       = requireModule('htmlbars-runtime').hooks,
          render      = requireModule('htmlbars-runtime').render;

      var templateSpec = compiler.compileSpec(src);
      var template = compiler.template(templateSpec);

      var env = { dom: new DOMHelper(), hooks: hooks, helpers: {} };
      var scope = hooks.createFreshScope();
      hooks.bindSelf(env, scope, data);

      var output = $('body')[0];
      var testDiv = $('#test')[0];

      var result = render(template, env, scope, { contextualElement: output });
      data.url = 'https://google.com';
      result.rerender();

      var dom = result.fragment;
      output.innerHTML = ''; // I don't want to remove old elements I want just update them
      output.appendChild( dom );
      var testDiv2 = $('#test')[0];
      console.log(testDiv2 === testDiv); // different nodes before and after render

and in index.html:

<html><body><div id="test">Howdy <a href>Bob</a></div></body></html>

It works but it seems to be producing new DOM elements every time I run it. As far as I understood from the Architecture.md, HtmlBars should use existing DOM elements and just update them if data changes. How to achieve this? Looks like I am missing something. Thanks for help!

mmun commented 9 years ago

This isn't possible right now. DOM is only preserved when using RenderResult#rerender or RenderResult#revalidate on an existing render result.

OrKoN commented 9 years ago

@mmun And is it hard to build a render result based on the existing DOM? I am trying to understand what is needed for this. I thought that ember fast boot is using something like that already or does it simply render the templates again even if there is html generated on the server?

mmun commented 9 years ago

It requires a significant amount of work. This is the next phase of fast boot, but it hasn't been worked on yet.

OrKoN commented 9 years ago

I see. @mmun, thanks for your reply.