Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'nunjucks' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
const app = express();
const config = {
port: 3000,
};
// Middlewares
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// View engine
app.set('view engine', 'html');
nunjucks.configure(path.join(__dirname, 'views'), {
express: app,
});
app.get('/', routes.index);
app.get('/action', routes.action);
app.get('/responsive', routes.responsive);
app.get('/form', routes.form);
app.get('/keys', routes.keys);
app.post('/result', routes.result);
app.get('/post/:id', routes.post);
app.get('/generate/:number', routes.generate);
app.listen(config.port, () => {
console.log(`App server running at http://localhost:${config.port}`);
});
app.use('/blind/nunjucks', function(req, res){
if(req.url) {
var url_parts = url.parse(req.url, true);
var inj = url_parts.query.inj;
var tpl = '';
if('tpl' in url_parts.query && url_parts.query.tpl != '') {
// Keep the formatting a-la-python
tpl = url_parts.query.tpl.replace('%s', inj);
}
else {
tpl = inj;
}
nunjucks.renderString(tpl);
res.end(randomstring.generate());
}
});
const { encodeURL, full_url_for } = require('hexo-util');
env.addFilter('uriencode', str => {
return encodeURI(str);
});
env.addFilter('noControlChars', str => {
return str.replace(/[\x00-\x1F\x7F]/g, ''); // eslint-disable-line no-control-regex
});
const atomTmplSrc = join(__dirname, '../atom.xml');
const atomTmpl = nunjucks.compile(readFileSync(atomTmplSrc, 'utf8'), env);
const rss2TmplSrc = join(__dirname, '../rss2.xml');
const rss2Tmpl = nunjucks.compile(readFileSync(rss2TmplSrc, 'utf8'), env);
const customTmplSrc = join(__dirname, 'custom.xml');
const customTmlp = nunjucks.compile(readFileSync(customTmplSrc, 'utf8'), env);
const urlConfig = {
url: 'http://localhost/',
root: '/'
};
describe('Feed generator', () => {
const hexo = new Hexo(__dirname, {
silent: true
});
const Post = hexo.model('Post');
const generator = require('../lib/generator').bind(hexo);
require('../node_modules/hexo/lib/plugins/helper')(hexo);
let posts = {};
const { readFileSync } = require('fs');
const cheerio = require('cheerio');
const { encodeURL, full_url_for } = require('hexo-util');
env.addFilter('uriencode', str => {
return encodeURI(str);
});
env.addFilter('noControlChars', str => {
return str.replace(/[\x00-\x1F\x7F]/g, ''); // eslint-disable-line no-control-regex
});
const atomTmplSrc = join(__dirname, '../atom.xml');
const atomTmpl = nunjucks.compile(readFileSync(atomTmplSrc, 'utf8'), env);
const rss2TmplSrc = join(__dirname, '../rss2.xml');
const rss2Tmpl = nunjucks.compile(readFileSync(rss2TmplSrc, 'utf8'), env);
const customTmplSrc = join(__dirname, 'custom.xml');
const customTmlp = nunjucks.compile(readFileSync(customTmplSrc, 'utf8'), env);
const urlConfig = {
url: 'http://localhost/',
root: '/'
};
describe('Feed generator', () => {
const hexo = new Hexo(__dirname, {
silent: true
});
const Post = hexo.model('Post');
const generator = require('../lib/generator').bind(hexo);
require('../node_modules/hexo/lib/plugins/helper')(hexo);
var app = express(),
oneDay = 86400000;
app.use(express.compress(), {
maxAge: oneDay
});
app.locals.assetsURL = env.assetsURL;
app.set('views', env.views);
app.set('redis', redis);
app.engine('html', nunjucks.render);
app.use(app.locals.assetsURL, express.static(env.assetsPath));
app.use(express.logger());
app.use(app.router);
nunjucks.configure(env.views, {
autoescape: true,
express: app
});
app.listen(env.port, function(err) {
if (err) {
console.error(err);
process.exit(-1);
}
// if run as root, downgrade to the owner of this file
if (process.platform.toLowerCase().indexOf('win') === -1) {
if ( process.getuid() === 0 ) {
fs.stat(__filename, function(err, stats) {
if (err) {
return console.error(err);
write: function(source, target, options) {
// console.log(source);
// console.log(options);
var dirname = path.dirname(source);
var basename = path.basename(source);
nunjucks.configure(dirname);
var data = nunjucks.render(basename, _.merge({}, options, {
_: _
}));
return writeFile(target, data, options);
}
return new Promise((resolve, reject) => {
// Create Nunjucks environment
let env = new nunjucks.Environment(
new nunjucks.FileSystemLoader(path.join(context, 'src'))
)
// Prefix URL to make it relative
env.addFilter('relative', (url) => {
if (file.split(path.sep)[0] === 'components') {
return `../${url}`
} else {
return url
}
})
// Add custom section tag
env.addExtension('SectionExtension', new SectionExtension())
// Add environment variables to Nunjucks
reset() {
this._prerenderers = [];
this.loader = new Loader({
sourceDir: this.sourceDir,
logger: this.logger,
errorHandler: error => {
this.emitter.emit("renderer:error", {
error
});
this.logger.error(error);
}
});
this.nunjucks = new nunjucks.Environment(this.loader, {
// dev: true
});
this.hljs = hljs;
this.markdown = new MarkdownIt({
html: true,
linkify: true,
langPrefix: "",
highlight: (code, lang) => {
if (lang === "text" || lang === "plain") {
return code;
}
return lang
? this.hljs.highlight(lang, code).value
// render the shell as a full page, minify it, and then split it up.
const SHELL_SPLIT_POINT = 'SHELL_SPLIT_POINT';
const data = {
ENV,
site: book.site,
articles: book.articles,
page: {
path: '',
private: true,
content: SHELL_SPLIT_POINT,
},
layout: 'shell.html',
};
const html = nunjucks.render('shell.html', data);
const processedHtml = processHtml(html);
const [shellStart, shellEnd] = processedHtml.split(SHELL_SPLIT_POINT);
await fs.outputFile(
path.join(config.publicDir, 'shell-start.html'), shellStart);
await fs.outputFile(
path.join(config.publicDir, 'shell-end.html'), shellEnd);
};
render(filename, text) {
let content = "";
let ext = path.extname(filename);
if (ext == ".json") {
content = JSON.parse(text);
}else if (ext == ".yaml" || ext == ".yml") {
content = jsyaml.safeLoad(text);
// content = JSON.stringify(yaml);
} else {
return "";
}
let swaggerUIPath = this.context.extensionPath + "/swagger-ui";
let destFile = this.context.extensionPath + "/swagger-ui/index.htm";
try {
nunjucks.configure(swaggerUIPath);
let res = nunjucks.render("index.njk", {swaggerUIPath: swaggerUIPath, content: content});
fs.writeFileSync(destFile, res);
// Turn windows file paths into a URI path:
destFile = destFile.replace(/\\/g, "/");
if (destFile[0] !== "/") {
destFile = "/" + destFile;
}
return vscode.Uri.parse('file://' + destFile);
} catch (error) {
console.error(error);
}
return "";
}
}