Add xhr support for render file in browser.

This commit is contained in:
ChenL
2018-01-12 10:53:43 +08:00
committed by Jun Yang
parent eee5649a47
commit c55f0234eb
10 changed files with 531 additions and 130 deletions
+42
View File
@@ -5,6 +5,7 @@ const tokenizer = require('./src/tokenizer.js')
const statFileAsync = require('./src/util/fs.js').statFileAsync
const readFileAsync = require('./src/util/fs.js').readFileAsync
const path = require('path')
const url = require('./src/util/url.js')
const Render = require('./src/render.js')
const lexical = require('./src/lexical.js')
const Tag = require('./src/tag.js')
@@ -73,6 +74,11 @@ var _engine = {
})
},
getTemplate: function (filepath, root) {
return typeof XMLHttpRequest === 'undefined'
? this.getTemplateFromFile(filepath, root)
: this.getTemplateFromUrl(filepath, root)
},
getTemplateFromFile: function (filepath, root) {
if (!path.extname(filepath)) {
filepath += this.options.extname
}
@@ -92,6 +98,42 @@ var _engine = {
}
})
},
getTemplateFromUrl: function (filepath, root) {
var fullUrl
if (url.valid(filepath)) {
fullUrl = filepath
} else {
if (!url.extname(filepath)) {
filepath += this.options.extname
}
fullUrl = url.resolve(root || this.options.root, filepath)
}
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
}
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
var tpl = this.parse(xhr.responseText)
if (this.options.cache) {
this.cache[filepath] = tpl
}
resolve(tpl)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(new Error(xhr.statusText))
}
xhr.open('GET', fullUrl)
xhr.send()
})
},
express: function (opts) {
opts = opts || {}
var self = this