75 lines
2.5 KiB
JavaScript
75 lines
2.5 KiB
JavaScript
const { dirname } = require('path');
|
|
const appDir = dirname(require.main.filename);
|
|
const fs = require('fs')
|
|
const langs = ["en", "es"]
|
|
const default_lang = "es"
|
|
|
|
function createCommonPath(router, path, renderParams = {
|
|
}, cb = () => {}){
|
|
const defaultParams = {
|
|
view: path,
|
|
}
|
|
const split_path = defaultParams.view.split('/')
|
|
const default_name = split_path[split_path.length-1]
|
|
defaultParams.name = default_name
|
|
defaultParams.stylesheet = renderParams.view === undefined ? '/public/styles/' + defaultParams.view + '/index' + '.css' : '/public/styles/' + renderParams.view + '/index' + '.css'
|
|
|
|
const possiblePathLogic = appDir + '/src/router/common_path_logic/' + defaultParams.view + '.js'
|
|
if (fs.existsSync(possiblePathLogic)){
|
|
cb = require(possiblePathLogic)
|
|
}
|
|
|
|
const possibleSettingsPath = '/src/router/common_path_settings/' + path + '.json'
|
|
|
|
let renderOptions = {...defaultParams, ...renderParams}
|
|
|
|
if (fs.existsSync(appDir + possibleSettingsPath)){
|
|
const fileGeneralParams = JSON.parse(fs.readFileSync(appDir + possibleSettingsPath))
|
|
renderOptions = {
|
|
...renderOptions,
|
|
...fileGeneralParams
|
|
}
|
|
}
|
|
renderOptions.lang = default_lang
|
|
renderOptions.langPath = ""
|
|
renderOptions = {
|
|
...renderOptions,
|
|
...getTlPartials(default_lang, path)
|
|
}
|
|
createPath('/' + path, cb, renderOptions, router)
|
|
for(let l in langs){
|
|
if(langs[l] == default_lang){
|
|
continue
|
|
}
|
|
const otherLangRender = {...renderOptions, ...getTlPartials(langs[l], path)}
|
|
otherLangRender.lang = langs[l]
|
|
otherLangRender.langPath = '/' + langs[l]
|
|
createPath(otherLangRender.langPath + '/' + path, cb, otherLangRender, router)
|
|
}
|
|
}
|
|
|
|
function createPath(path, cb, renderOptions, router){
|
|
router.get(path, async (req, res) => {
|
|
const cb_params = await cb(req, res)
|
|
const finalOptions = {...renderOptions, ...cb_params}
|
|
res.render(finalOptions.view, finalOptions)
|
|
})
|
|
}
|
|
|
|
function getTlPartials(lang, path){
|
|
try{
|
|
const partialsDic = {}
|
|
const tlPath = "translations/" + lang + '/' + path
|
|
const filenames = fs.readdirSync(appDir + '/views/partials' + '/' + tlPath)
|
|
filenames.forEach(f => {
|
|
const viewName = f.split('.hbs')[0]
|
|
partialsDic["tl_" + viewName] = tlPath + '/' + viewName
|
|
})
|
|
return partialsDic
|
|
}catch(e){
|
|
|
|
}
|
|
}
|
|
|
|
module.exports = createCommonPath
|