Mithril is a small, high-performance JavaScript MVC framework. The Flarum forum project uses it on the front end, and one of Mithril’s strongest traits is how compact its API is. That makes it a nice fit for pulling data from the WordPress REST API and rendering it directly in the front end.
The simplest way to understand the workflow is to look at a basic example that reads WordPress posts from the REST API.
Get WordPress posts with Mithril through the WordPress REST API
var posts = {};
// Model: get WordPress posts with Ajax
var Post = {
list: function () {
return m.request({
method: "GET",
url: "/wp-json/wp/v2/posts/"
});
}
};
// Controller: pass data between model and view
posts.controller = function () {
var posts = Post.list();
return {
posts: posts
}
};
// View: render the data
posts.view = function (ctrl) {
return m("div.list-group", [
ctrl.posts().map(function (post) {
return m("a.list-group-item", {href: '#single/' + post.id}, [
m("h4.list-group-item-heading", post.title.rendered),
m("p.list-group-item-text", m.trust(post.excerpt.rendered))
]
);
}),
m.component( title, {data: "所有文章"})
]);
};
Mount the application with m.route
After the application logic above exists, the data still needs to be mounted into the page. That is what m.route does. In the following example, the application is mounted into the DOM element whose ID is ucenter.
m.route.mode = "hash";
m.route(document.getElementById("ucenter"), "/", {
"/": posts
});
This is one of the simplest ways to combine Mithril with the WordPress REST API. At first glance it may still look a little abstract, but the real value of the REST API is that it separates the front end from the back end. The back end only has to provide clean endpoints; the front end is free to build whatever interface it wants on top of them. That separation becomes especially useful in larger applications where cleaner code structure and easier maintenance matter much more.
