当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于react后端渲染模板引擎noox发布使用

基于react后端渲染模板引擎noox发布使用

2018年01月28日  | 移动技术网IT编程  | 我要评论

react 组件化思想受到越来越多开发者的关注,组件化思想帮助开发者将页面解耦成一个一个组件,代码更加模块化, 更易扩展。而目前流行的后端模板引擎如 ejs, swig, jade, art 共同的问题是:

  1. 需要学习各类模板引擎定义的语法,如 {{if}}, {{loop}}
  2. 对组件化支持不够强,实现复杂,不易用

针对以上痛点,笔者基于 react 造出了 noox 这样一个工具,专注于后端模板的解析,让模板解析更加简单,易用。

使用方法

安装

npm install noox

简单的 demo

模板代码

首先创建组件目录和增加模板文件

mkdir components && cd components
vi head.jsx

head.jsx 内容如下:

<head>
 <title>{title}</title>
 <meta name="description" content={props.description} />
 <link rel="stylesheet" href="./css/style.css" rel="external nofollow" rel="external nofollow" />
</head>

node.js code

const noox = require('noox');
const nx = new noox(path.resolve(__dirname, './components'), {title: 'noox'});
let output = nx.render('head', {description: 'hello, noox.'})

输出

<head>
 <title>noox</title>
 <meta name="description" content="hello, noox." />
 <link rel="stylesheet" href="./css/style.css" rel="external nofollow" rel="external nofollow" />
</head>

原理

noox 在 react 的 jsx 的基础上,简化了组件引用和创建,假设创建一个目录结构如下:

components/
 header.jsx
 body.jsx
 layout.jsx

运行如下 nodejs 的代码:

nx = new noox(path.resolve(__dirname, './components'))

将会创建三个组件:

  1. header
  2. body
  3. layout

然后通过 nx.render 渲染

nx.render('body', props)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网