I’m thinking of setting the form action URL dynamically with JavaScript to stop spam bots after reading this article. In this way, the JavaScript needs to load parameters from the site config.
You should not want to do this. JS files are code and combining code and templating leads to madness. Trust me from experience on this one, the results are instantly unreadable spaghetti.
I tried loading a JS file with Hugo template code with these lines
ERROR 2019/07/26 18:47:58 Rebuild failed:
ERROR 2019/07/26 18:47:58 Failed to render pages: render of "page" failed: "/home/vin100/huginn/layouts/_default/single.html:71:63": execute of template failed: template: _default/single.html:71:63: executing "main" at <resources.ExecuteAsTemplate>: error calling ExecuteAsTemplate: must provide targetPath, the template data context and a Resource object
For the record, executing a JS file as a template is an example of “combining code and templating” which “leads to madness”.
Here is something simple you can do instead if you think you need to obscure the URL of your action (not sure that’s necessary, but let’s assume it is):
In Hugo, you are going to use templates to add attributes:
(function () {
var form = document.querySelector("[data-secret-action]");
if (!form) {
return;
}
var url = btoa(form.dataset.secretAction);
form.action = url;
})();
Following this pattern whenever you need to pass data from Hugo to JavaScript is the only road to sanity. Executing JS as a template, whether the JS on is on the page or in a separate file, will lead to endless suffering because your code has two meanings at once—the JS meaning and the Hugo meaning—and those two meanings are interwoven with no clear delineation.