irrationalistic
irrationalistic

Reputation: 108

Render a meteor reactive variable from a database field

If I have a field in my DB that contains a string like "Hello {{currentUser}}," is there a way to allow that value to retain reactivity when rendered into a template? I am also looking to see if I can somehow inject my own variable into the output by running it through a helper and handling string replacement.

Thoughts?

Upvotes: 1

Views: 116

Answers (1)

irrationalistic
irrationalistic

Reputation: 108

One solution I've come up with thus far:

The message stored in the db is something like: "Hello, [user], how are you?"

I then render the message from the DB as usual with {{#each}} and a predefined template.

When the message is actually rendered, I pass it through a helper. The helper replaces all []'s with <span class="$1"></span> so that I can target each item directly.

Once the message template's rendered() is called, I know that the message body contains the cleaned and prepped content (with the spans), so I use this.$('.user').each() and loop over each instance of the spans.

I've also created a special template in my page called 'placeholderUser' that only contains a call to {{user}}. I've added Template.placeholderUser.user = function(){} to the code to pull through a value and maintain reactivity.

Whew! Now that I have the structure set up, when looping through in the "each," I can call: UI.insert(UI.render(Template.placeholderUser), el), which will render the template in the given span and maintain all reactivity.

It's super hacky, but it works. Any other, better, solutions out there?

Upvotes: 1

Related Questions