Wrap the contents of a template in an element


#1

How can I wrap the contents of a template in an element? (say an <h1></h1>)

The ideal solution would wrap the contents before Blaze materializes the contents of the template on the page.

For example if I have the following template:

<template name="greeting">
  Hello
</template>

The output would be:

<h1>"Hello"</h1>

Instead of the usual:

"Hello"

#3

You can wrap the renderFunc like so: https://github.com/stubailo/meteor-components/blob/9a9d2ca8254f1aef05fa732c283d6ea606b290ba/packages/components/components.js#L100-L103

This is some super old code, don’t judge me!


#4

Just what the doctor prescribed. Thanks man.

For the wanderer who lands here, this is what I ended up using (for now at least):

  Blaze.Template.prototype.wrapRender = function(){
    var template = this;
    var name = template.viewName.split(".")[1];
    var oldRenderFunc = template.renderFunction;
    template.renderFunction = function() {
      return HTML.getTag(name)(oldRenderFunc.call(this));
    };
  };

  Template.greeting.wrapRender();

#5

May I inquire the usecase for this? Why not inside the template? :sunny:


#7

Oh. Didn’t know that was a thing


#8

Yeah I’m not sure if there are too many use cases for it. I did it because I was trying to build a framework type thing.


#9

I didn’t think it would be interesting. My two use cases are better XPATH support (it’s a lot easier to locate a template instance on the page if it’s wrapped with something), and CSS styles that only apply to specific templates.


#10

Yep, that’s exactly what I was doing! in my case I wanted to wrap all templates with an element called the same as the template to be able to find them easily with jQuery.


#11

why not just use spacebars custom block helpers? for the OP usecase