Use handlebars template helpers in hapijs - javascript

I'm using jquery's typeahead in hapijs using a handlebar view. It works with static source data. I want to use data from a postgresql-database but I don't know how to include the pg-bluebird npm module.
I've done a similar jquery typeahead in meteorjs where I get the source from a mongodb collection using the template name and then call a template event from javascript like:
html:
<template name="participantItem">
... html form input etc. ...
</template>
javascript:
Template.participantItem.events({
'click .edit': function (e) {
e.preventDefault();
$("#club").autocomplete({
/* query remote source */
});
}
});
When I try to add <template name="foo"> to my html file in hapijs it loads the content but the page is not rendered except for the header and footer.
I like the way meteorjs is using helper templates and events and would like to do it the same way in hapijs.
I ended up including javascript to test typeahead with static data in the html file but it does not appear to be very elegant.
<div class="container">
<div class="row">
... content using some json data ...
</div>
</div>
<script type="text/javascript">
$(function () {
$('#states').autocomplete({
delay: 500,
minLength: 2,
source: states
});
}
</script>
I call the view like this from index.js:
var Pgb = require('pg-bluebird');
var pg = new Pgb();
var db = "postgresq://claus#localhost/karusellrenn";
exports.register = function (plugin, options, next) {
plugin.route([
{
method: 'GET',
path: '/participants',
handler: function (request, reply) {
.then(function (result) {
cnn.done();
reply.view('participants', { p: result.rows});
.catch(function (error) {
console.log(error);
});
}
}
]);
next();
};
Can I use handlebars in hapijs the same way I use handlebars in meteorjs like <template name="foo"></template> and then make use of a javascript helper like Template.foo.events({});?
And if not, can I use pg-bluebird included in index.js in my handlebars view inside in the handlebars view?

Related

Vuejs - Render raw html links to <router-link>

I;m new to VueJS and I'm making some weird experiments. I build a backend service using python/flask and this backend provide me a string of html code with many tags inside, I want to render this inside my Vue app, I have a method for calling the backend that looks like this:
async execute (method, resource, data) {
return client({
method,
url: resource,
data: data
}).then(async req => {
return req.data.html
})
},
callBack (id) {
console.log(id)
return this.execute('post', '/content/', {body: { 'id': id }})
}
And in the .vue file I have:
export default {
data () {
return {
loading: false,
launch: [],
html: 'none',
page: this.$route.params.article
}
},
beforeMount () {
console.log('beforeee')
this.html = api.callBack(this.page)
},
methods: {
async launch () {
this.launch = ''
this.html = await api.callBack(this.page)
}
}
}
so when I call the launch function it populates this.html, and this html variable lives in a v-html.Everything seems to work i get the html and render it in de container but the links are broken, the links should point at the same app something like #/test/linkvalue, but as they are tags, and in vue you have to use they doesn't work.
There is a way to achieve this "dynamic re route" or I'm doing something too weird?
The links are plenty, since they are scraped from the web, so manually parsing is not an option.
JSFiddle
Thanks in advance for your help
Also, you shouldn't return the raw html. Just return the paths for the routes and then loop the paths and create links that way.
You can use the v-html vue directive to output raw html.
https://jsfiddle.net/eywraw8t/66262/
new Vue({
el: "#app",
data: {
rawhtml: "<h1 style='color: red;'>Hi, I am raw html.</h1>"
},
methods: {
}
})
<div id="app">
<div v-html="rawhtml"></div>
</div>

How to write Vue js code in separate file and include in laravel

How to write Vue js code in separate file and include in laravel
Blade page code?
Am also using gulp file.
#section('js')
<script>
new Vue({
// Defining a element.
el: '#branddashboard-html',
data: {
// Defining data variable.
brandStats: null
},
// On load functionality.
created: function () {
// Initializing method.
this.getData();
},
},
// Methods to implement.
methods: {
getData: function () {
self.brandStats = null;
$.get('brand-stats/' + userId + '/' + period, function (data) {
self.brandStats = data;
});
}
}
});
</script>
#endsection
I think this is no the best idea. I think, the Blade's Templates only works in the views folder. Your frontend logic is now managed with Vue Component System, in this MVVM vue way. Hope this be usefull to you

Updating template after http call in Meteor

I'm making a new app with Meteor and I'm trying to get some public Github repos. I've written this call-method tuple:
Meteor.call('getRepositories', function(error, results) {
console.log(results);
});
Meteor.methods({
getRepositories: function(user) {
var response = Meteor.http
.call('GET','https://api.github.com/users/{username}/repos');
return response.data;
}
});
The problem is... how can I achieve to update the template with repositories names?
Thanks!
// your_tmpl template {{#each repos}}
{{name}}
{{/each}}
// js template manager
var reactiveRepos = new ReactiveVar([]);
Meteor.call('getRepositories', function(error, results) {
reactiveRepos.set(results); });
Template.your_tmpl.helpers({
repos: function() {
return reactiveRepos.get();
} });
// server.js
Meteor.methods({
getRepositories: function(user) {
var response = Meteor.http
.call('GET','https://api.github.com/users/{username}/repos');
return response.data;
}
});
You could use ReactiveVar (http://docs.meteor.com/#/full/reactivevar_pkg) package, that allow us to create reactive variables and use it in reactive environment, like helpers. Sure, you may want use it inside templates hooks as onRendered or onCreated for example, and bind it to your template.

live update view in ember

I build application using web-socket and I want dynamically change view
I have code in my model:
model: function () {
var store = this.store;
var socket = new_socket();
socket.on('message', function (message) {
store.push('record',message);
});
return store.find('consultation');
}
And data successfully loading into ember store, but ember doesn't update view.
What I need to do?
For example when I use save all works fine:
var record = this.store.createRecord('record',{});
record.save()
UPDATE:
I found this solution:, but it's also not working
My controller (consultation.js):
export default Ember.ObjectController.extend({
needs: ['application'],
records: function() {
console.log(this.get('store'));
return this.get('store').filter('record', function(record) {
console.log(record);
});
}.property('records'),
Template:
{{#each item in controller.records}}
{{/each}}
Model consultation looks like this (with hasMany field):
export default DS.Model.extend({
records: DS.hasMany('record', { async: true }),
});
Second console.log is not printing,
I solved it like this
var obj = store.push('record', jsonObj.message);
this.controllerFor('consultation').get('records').pushObject(obj);
But it's looks like not good. In which way I can make auto synchronization between model and controller
You have computed properties that are dependent on themselves in your controller. Also, you really should not be pushing anything to the store, conceptually, when you receive something on your socket, your model changed, you want to capture that notion in your code, so you really should be updating the model when you get a socket message. The way I would do this would be to do something like the following:
in the router,
model: function() {
var records = this.store.find('consultation',{});
var socket = new_socket();
socket.on('message', function (message) {
records.pushObject(message);
});
return records;
}
The controller does not need to have any computed properties at all.
and in the template, the code would just be:
{{#each content}}
//do something here
{{/each}}
I'm a little confused about your use of consultation and record in the code.

Template doesn't show up when wrapping it with {{#with}}?

I'm following the Discover Meteor book
For some reason, the content in edit_post.html doesn't show up with the {{#with post}}:
<template name="postEdit">
{{#with post}}
<form class="main">
<div class="control-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" type="text" value="{{url}}" placeholder="Your URL"/>
</div>
</div>
.
.
.
</form>
{{/with}}
</template>
the content of post_edit.js:
Template.postEdit.helpers({
post: function() {
return Posts.findOne(Session.get('currentPostId'));
}
});
Template.postEdit.events({
'submit form': function(e) {
e.preventDefault();
var currentPostId = Session.get('currentPostId');
var postProperties = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
}
Posts.update(currentPostId, {$set: postProperties}, function(error) {
if (error) {
// display the error to the user
alert(error.reason);
} else {
Router.go('postPage', {_id: currentPostId});
}
});
},
'click .delete': function(e) {
e.preventDefault();
.
.
.
}
}
});
route.js:
this.route('postEdit', {
path: '/posts/:_id/edit',
data: function() { return Posts.findOne(this.params._id); }
});
The template shows up if I remove the {{#with post}}.
I'm not sure if this is an error in the book, or whether I'm doing something wrong. I'm a Meteor beginner so I have no clue.
Any suggestion to fix this?
The template helper post calls a Session variable that is never set so I think that findOne() returns a falsy value. So {{#with post}} is correctly keeping the template from displaying. Without the {{#with post}} your template is able to display a post from the data function in the router. You are calling findOne() looking for the same data twice but either method will work to get the data you want for the template.
If you want to use {{#with}} you can change your route.js to:
this.route('postEdit', {
path: '/posts/:_id/edit',
before: function() { Session.set( "currentPostId", this.params._id ); }
});
I'm looking at the code from the book and I cannot see the with block you are referring to.
In fact, it should not be there because the data context of the template is already set by the router.
Your template helper (post) is not supposed to be there since it is both unnecessary and in fact there is no already set session variable so your get returns null as expected.
Just delete your helper and the with block and let iron router provide the data context as it already does.

Categories

Resources