[solved] Unique Blaze Reactivity Issue

I have a unique Blaze reactivity issue on Meteor V2.16.

In a template I want to pull in some html that I generate on the fly using a helper.

If I use {{ myHelper }} in the template, the result is simply the Html text displayed verbatim on the page as a text string

<img src="bla.jpg">bla</img> appears

If I use {{{ myHelper }}} in the template, the result is the interpreted html
(the actual image appears)

But that line of html is not reactive, if for example the result of that image changes while the page is being displayed. Is it supposed to be??

But the new image appears if i manually refresh the page.

Any ideas how to make that portion of the html reactive, or any ideas what I may be doing wrong? I am always subscribed to all the images - so I don’t see that that is the issue.

Hello, there is more than one method to do what you want in blaze. First of all, to answer your question, as it will be seen in the code block below, the helper defined for the name template is triggered by a reactive variable to run again at the click time.

Template.name.onCreated(function () {
  this.refresh = new ReactiveVar(null)
})

Template.name.helpers({
  getSomeHtml: function() {
    Template.instance().refresh.get()

    return '<img src="bla.jpg">bla</img> appears'
  }
});

Template.name.events({ 
  'click #refresh': function(event, template) { 
    template.refresh.set(Random.id())
  } 
});

However, I recommend you to do this directly with reactive variables.

global-helper.js

Template.registerHelper('getVariable', function (variableName) {
  return Template.instance()[variableName]
})
Template.name.onCreated(function () {
  this.html = new ReactiveVar(null)
})

Template.name.onRendered(function() { 
  const self = this

  this.autorun(function() { 
    // calc html

    self.html.set(html)
  })
})

Template.name.events({ 
  'click #refresh': function(event, template) { 
    const self = this

    self.html.set('html')
  } 
});
<template name="name">
  <div>
    <button id="refresh">Refresh</button>

    {{#let html=(getVariable 'html')}}
      {{{html.get}}}
    {{/let}}
  </div>
</template>

Finally, be careful when using the {{{}}} operator, don’t run html code you don’t trust directly.

1 Like

Thank you. I will give this a try today.

1 Like