Reputation: 2473
I'm new in Meteor.js and have a basic question. I want to render a template with data from server side route with iron-router module. I used where: 'server' in my route obtion (from this link) but render function ( this.render() ) not fired.
I successfully done this by using NodeJS Request and Response object (as above example) but I want to pass data to template and render the template from server.
This is my route code:
Router.route('/movie/title', function () {
var request = Meteor.npmRequire('request');
var future = new (Npm.require('fibers/future'))();
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
future.return(body);
}
else {
future.throw(error);
}
})
var myResult = future.wait();
console.log(myResult);
this.render('test', {
data: { result: myResult }
});
}, { where: 'server' });
And this is my template code:
<head>
<title>Search your favorite movie</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button>Click Me</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
<template name="test">
{{result}}
</template>
Please guide me.
Upvotes: 2
Views: 892
Reputation: 1287
From the Iron Router Cheatsheet, render is not available on the server:
# When you define a server route (via where: 'server'), you need to define the action function, and use in a fairly simplistic way, much like express. # The render method is not available.
It doesn't appear to have been updated in 6 months, and I can't find anything in the Iron Router Guide or the readme on GitHub about it only being available on the client, but my guess is that's the problem.
If you really need to render from the server, you might check out meteorhacks:ssr (server-side rendering); there appears to be a pretty in-depth post about it on the meteorhacks site as well.
From the readme of that package, it looks like the way forward with your particular problem is to define your templates in the private/ directory, then call the compileTemplate method on the server:
<!--template in private/hello.html-->
<template name="hello">
<button>Click Me</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
<!--Another template in private/test.html -->
<template name="test">
{{result}}
</template>
You'll want to define any helpers on the server as well, and compile the template on the server:
// in server/test.js
SSR.compileTemplate('test', Assets.getText('test.html')
You can then use the SSR package to render the template on the server with data, which will return the HTML as a string; you could implement it with a Meteor Method to get the HTML back to the client:
// You can call this method from the client to get the rendered template back:
Meteor.methods('renderTest', function(data) {
return SSR.render('test', data);
});
See this question for significantly more detail on using SSR and iron:router in conjunction.
Upvotes: 3