What is import of html file?

Hello everyone!

What is import of html file need for?

It is like file inclusion?
Why it is in js file then?

import { Template } from 'meteor/templating';
 
import './body.html';
 
Template.body.helpers({
  tasks: [
    { text: 'This is task 1' },
    { text: 'This is task 2' },
    { text: 'This is task 3' },
  ],
});

Look here (official tutorial):

https://www.meteor.com/tutorials/blaze/templates

1 Like

It’s a load order thing. This way no matter what this JS file is called, you know that Template.body will exist before you use it.

2 Likes

I think what he meant was why we are importing the .html file inside the .js file:
import './body.html';

1 Like

That’s what I answered, but I guess not very well :slight_smile:

This shouldn’t be confused with imports in certain config files which basically get substituted with their contents. i.e., in the example above, no HTML is being “imported” to inside the JS file.

The full import lines are clearer: import { Template } from 'meteor/templating'. That’s saying, meteor/templating should run before this file, and whatever it exports, put into my local Template variable.

The shorter line import './body.html' doesn’t make use of any exports (since Blaze/Spacebars stores all compiled templates under the Template object, which we already imported above), however, we’re still saying main.html must be evaluated before the current file, and hence, that Template.body will exist on the Template object, before the current file is run.

Obviously this isn’t strictly required because of the backwards compatible load order rules, but it’s a good practice moving forward (same as with all the import statements in general), it’s also makes it much clearer that this code wouldn’t work properly if it ran after main.html.

I hope this explanation was clearer but please let us know if not and hopefully someone else can do better :slight_smile:

4 Likes

I do see this as a nice opportunity for MDG to make Blaze more in-line with the new modules in terms of usage. Something like:

import body from './body.html';
 
body.helpers({
  tasks: [
    { text: 'This is task 1' },
    { text: 'This is task 2' },
    { text: 'This is task 3' },
  ],
});

Note: THIS CODE DOES NOT WORK AT THIS MOMENT

@nathantreid is on this:

1 Like

Note that my Blaze Modules package as mentioned by @gadicc doesn’t handle the use case you presented since the “body” template is a “special” global template.
Perhaps I should consider making it (and all other global templates) non-default exports, so you could do:

import { body } from './body.html'; `
2 Likes

Yeah actually that’s nicer, since the user might have multiple components per file, too. It’s clearer and forces the user to exactly match the component name.

Cool, cool :sunglasses: