I'm learning how to develop a node application. It's an app where people can post events happening around the city.
I have an ejs file, new.ejs, that allows users to submit a new event. Obviously there is an event start time and end time. I want to make sure that the end time is AFTER the start time, so I simply added a script to do that, as follows:
<!-- EVENT DATE AND TIME -->
<div class=row>
<!-- DATE -->
<div class="form-group col-md-4">
<label for="date">Date *</label>
<input name="date" type="date" class="form-control" id="date">
</div>
<!--START TIME -->
<div class="form-group col-md-4 ">
<label for="starttime">Start Time *</label>
<input name="starttime" type="text" class="form-control" id="starttime">
</div>
<!--END TIME -->
<div class="form-group col-md-4 ">
<label for="endtime">End Time *</label>
<input name="endtime" type="text" class="form-control" id="endtime">
</div>
<script type="text/javascript">
$('#starttime').timepicker();
$('#endtime').timepicker({
'minTime': '12:00am',
'showDuration': true
});
$('#starttime').on('changeTime', function() {
$('#endtime').timepicker('option', 'minTime', $(this).val());
});
</script>
</div> <!-- END OF ROW -->
Now this works just fine, it does what I want it to do.
However, I know that EJS is designed to take back-end (node) javascript code and render it out into the view.
My question is:
Is adding front-end code between tags a hack? I.e, is this proper coding practice? If not, what is a better way of doing this?
Right now, I just have a small amount of code between my script tags. As I continue to develop the application, what happens if the code gets way too long? Should it remain in the ejs file? Seems too messy...
If your app is server-side rendered (not a Single Page Application), then your approach is sound.
You can put the your code in JS files in a /public
folder and configured your node server to serve those files as static files, and add <script>
tags in the .ejs
files that reference those JS files.
I have a sample project with such an implementation. This will be your ejs file (jade for my case) and this is where you put your script files. Lastly, configure your app to serve static assets from a directory like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With