问题
I am trying to render a template in Vapor 3 with Leaf. Most of my HTML is in my base.leaf. In the login.leaf
template, I need to add a JS script. Trouble is when it gets to the function it breaks and renders the function. Can anyone tell me how to add these properly? Thanks for your help in advance. Here's what is giving me problems:
#set("content") {
<h1>#(title)</h1>
<div id="logo"><img src="images/global/journey_trax_logo.png" alt=""/></div>
<div id="sheet1" class="form_sheet">
<input type="text" class="text_input" id="name_field" placeholder="NAME">
<input type="password" class="text_input" id="password_field" placeholder="PASSWORD">
<div id="continue_btn1" class="text_btn" onClick="logIn();">Continue</div>
<p> </p>
</div>
<script>
var user_name = readCookie("user_name");
var user_password = readCookie("user_password");
document.getElementById("user_name").value = user_name;
document.getElementById("user_password").value = user_password;
function logIn() {
var baseURL = window.top.location.href;
if (baseURL.indexOf("#") != -1) {
baseURL = window.location.href.split("#")[0];
}
var url = baseURL + "login";
console.log("[logIn] post to URL: "+url);
console.log("[logIn] name: "+user_name+", password: "+user_password);
$.post( url,
{
name: user_name,
password: user_password
},
function(data) {
// Do something with the return data?
console.log("[logIn] callback data: "+data);
console.log("[logIn] handle succes or error");
//
parent.loadHTML('screens/home.html');
}
);
}
</script>
<style>
.text_input, select {
width: 100%;
margin-bottom: 30px;
}
.text_btn {
width: 100%;
margin-top: 20px;
cursor: pointer;
}
</style>
}
#embed("base")
回答1:
Your fundamental problem is that the }
characters in the Javascript are being captured by Leaf
because it is inside the #set
tag. You have two choices:
Leave it where it is escape all the instances of
}
inside your<script>
tag to\}
. As far as I can tell, it doesn't need{
escaping in the same way; presumably, this is because there isn't aLeaf
tag immediately preceding. This works reliably and you can useLeaf
to generate your javascript server-side before sending it to the client.Move the
<script>
and contents above (i.e. outside) the#set
tag. If you do embed anyLeaf
tags inside the javascript, you'll need to start escaping any}
characters belonging to the Javascript as option 1.
来源:https://stackoverflow.com/questions/59586284/vapor-3-rendering-leaf-template-with-script-inline