Skip to content

Instantly share code, notes, and snippets.

@xor-gate
Last active September 20, 2021 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xor-gate/73d81dcf5e0302e29c518f1db57935d1 to your computer and use it in GitHub Desktop.
Save xor-gate/73d81dcf5e0302e29c518f1db57935d1 to your computer and use it in GitHub Desktop.
QJSEngine template engine
#include <QJSEngine>
#include <QDebug>
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QVariantMap>
QString loadFile(QString fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Unable to open file " << fileName;
return QString("");
}
QTextStream fstream(&file);
QString data = fstream.readAll();
file.close();
return data;
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QJSEngine js;
auto data = loadFile("ejs.min.js");
QJSValue result = js.evaluate(data, "ejs.min.js");
if (result.isError()) {
qDebug() << "result: " << result.property("lineNumber").toInt() << ":" << result.toString();
}
auto tmpl = loadFile("main.ejs");
js.globalObject().setProperty("template", tmpl);
QString jsRender("ejs.render(template, data);");
QVariantMap renderData;
QStringList users;
users << "jerry" << "steven" << "maurice";
renderData.insert("users", users);
js.globalObject().setProperty("data", js.toScriptValue(renderData));
result = js.evaluate(jsRender, "render.js");
if (result.isError()) {
qDebug() << "result: " << result.property("lineNumber").toInt() << ":" << result.toString();
} else {
QTextStream ts( stdout );
ts << result.toString();
}
return 0;
}
<% if (users) { %>
There are <%- users.length %> users:
<% users.forEach(function(user) { -%>
- <%= user %>
<% }); %>
JSON: <%- JSON.stringify(users) -%>
<% if (users.includes("jerry")) { -%>
There is a user named jerry!
<% } -%>
<% users.forEach(function(user) { -%>
<%_ switch (user) {
case 'steven' : -%>
There is a user named steven!
<% break;
} -%>
<% }); -%>
<% } -%>
SOURCES = main.cpp
QT += core qml
Download ejs.min.js from https://cdn.jsdelivr.net/npm/ejs@3.1.6/ejs.min.js
See also https://cpp.hotexamples.com/examples/-/QJSEngine/toScriptValue/cpp-qjsengine-toscriptvalue-method-examples.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment