Closed eduardhasanaj closed 5 years ago
Hi @eduardhasanaj2, thanks for the question! Does this interactive demo help?
Hi @nebrelbug , thank you for your time. I was wondering if with precompile we assume that the functions are stored in file during webpack packaging. This scenario is handled by handlebars where we can get compiled result in files so we do not have to precompile at start.
Hi @eduardhasanaj2! You can do Sqrl.renderFile(filePath, options)
if you want to render a template directly from a file. This will also cache the template function.
As of right now, you have to load the templates yourself, usually with renderFile
(you can't just require
them in Webpack). I'm planning on writing a Webpack loader soon though!
I am just confused with precompilation. I thought that there was a way that we can precompile into functions not in runtime. So we put some files that hold the templates and as result we take precompiled template functions as in case of handlebar.
Hi @eduardhasanaj2, sorry for the late reply!
Here is an example of precompiling a Squirrelly template:
In precompile.js
fs = require('fs')
var Sqrl = require('squirrelly')
var template = 'This is a template. My favorite template engine is {{fav}}'
fs.writeFileSync(
'precompiledTemplate.js',
'var template = ' + Sqrl.Compile(template).toString()
)
Then run node precompile.js
This will create a file called precompiledTemplate.js
that contains the precompiled function.
To use your precompiled template in a website, you can do this: In the same directory, create index.html
<!DOCTYPE html>
<html>
<head>
<title>Example Doc</title>
<script src="./precompiledTemplate.js"></script>
<script src="https://unpkg.com/squirrelly@latest/dist/squirrelly.runtime.js"></script>
</head>
<body>
<p id="result"></p>
<script>
window.onload = function () {
document.getElementById('result').innerHTML = Sqrl.Render(template, {fav: "Squirrelly!"})
}
</script>
</body>
</html>
First, we link to the Squirrelly Runtime and the precompiled template (which is stored in the global variable template
).
Then, we render template
with options. If you open up the file in the browser, you can see that the template displays.
I hope this helps! Feel free to ask any more questions you might have.
Thats what I wanted. Thank you.
You're welcome. Feel free to ask any more questions!
@nebrelbug What's difference between compile() and renderFile()?
Would like to precompile templates at build time and have running application using any web framework (http, express or fastify as example) use the precompiled template at request time. Can you show how to do?
Is such precompilation use case possible?
I am trying to understand if we can precompile with webpack. With handlebars we just invoke handlebar compiler or include handlebar loader. After precomplation we have generated function. How can we achieve that in Squirrelly?