I am working on an app with NodeJS and have been able to use handlebars and partials without much trouble. I am getting to the point where I have view
and edit
forms for a car.
For example, after the user submits an application I have "View" and "Edit" links that go to localhost:3000/cars/:id/view
and localhost:3000/cars/:id/edit
, respectively.
The only difference between these two links is that the "View" page has the form with readonly="readonly"
and the "Edit" does not have the readonly
attribute.
What I would like to do
cars/view
{{ >car_form readonly=true }}
cars/edit
{{ >car_form readonly=false }}
<button type="submit">Submit</button>
Is this possible with handlebars templates? Or is there something similar I can do to get the result I want?
Thank you!
You're passing in the readonly
option correctly, now all you need to do is use it when rendering your form.
To do that I've used a helper to render the form via JavaScript, where we can do anything we like using the Hash Arguments funtionality Handlebars supports.
// Let's pretend this is the user input you're holding in Node.js // and want to render in your view and edit forms. var userInput = { "name": "Bob", "tagline": "Yep, I'm Bob!" }; Handlebars.registerHelper('userForm', function(options) { var formOpening = options.hash.readonly ? "<form readonly=\\"readonly\\">" : "<form>"; // Notice that I feed in `userInput` as the context here. // You may need to do this differently, depending on your setup. var formContents = options.fn(userInput); return formOpening + formContents + "</form>"; }); var userFormTemplate = Handlebars.compile(document.getElementById("userForm-template").innerHTML); var pageTemplate = Handlebars.compile(document.getElementById("page-template").innerHTML); Handlebars.registerPartial('userForm', userFormTemplate); document.getElementById("wrap").innerHTML = pageTemplate();
<div id="wrap"></div> <script id="page-template" type="text/x-handlebars-template"> <h2>View</h2> {{> userForm readonly=true}} <h2>Edit</h2> {{> userForm readonly=false}} </script> <script id="userForm-template" type="text/x-handlebars-template"> {{#userForm readonly=readonly}} <input type="text" name="name" value="{{name}}" /> <input type="text" name="tagline" value="{{tagline}}" /> <button type="submit">Submit</button> {{/userForm}} </script> <script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v4.0.5.js"></script>
In the above snippet, the readonly="readonly"
attribute is being added to the form beneath the "View" heading.
Note that on my browser, this does not actually make the form read-only - I'm not sure if you've got another library or something to handle that?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.