Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using script tags in ejs files?

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:

  1. 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?

  2. 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...

like image 518
Asool Avatar asked Oct 17 '22 20:10

Asool


1 Answers

  1. If your app is server-side rendered (not a Single Page Application), then your approach is sound.

  2. 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.

like image 200
Yangshun Tay Avatar answered Oct 20 '22 09:10

Yangshun Tay