Search code examples
hamlerbmiddleman

In Middleman that uses layout files, how can we append a js file for a specific html file during compile time?


I'm using Middleman, and I have a layout file that appends the jQuery CDN at the bottom for all .html.haml files. The layout file adds the jQuery CDN after all the html elements have been rendered.

One of my .html.haml files will have an additional js file that uses jQuery; however, it needs to see the jQuery CDN loaded first.

How can I tell Middleman that during compile time, append the js file for this specific .html.haml file? I tried appending = javascript_include_tag "jsfile" at the bottom of my .html.haml file, but it errored out because it needed jQuery loaded first which won't happen until I reach the end of the layout file.

layout file:

!!! 5
%html{lang: 'en'}
  %head
  %body{class: current_page.data.body_class || 'page'}
    = yield
    // jQuery
    = javascript_include_tag  "//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"
    //I need to insert my js file here, but only for a specific HTML file.

P.S. Also, I need to place the jQuery at the bottom of the file to make rendering more efficient, so I can't place it in the head.


Solution

  • Providing my answer here after figuring out what worked for me:

    First, I had to set a flag via index_options in the .html.haml file:

    ---
    title: My Site
    index_options: target_file
    ---
    

    Then, I had to update the layout file with an if statement

    !!! 5
    %html{lang: 'en'}
      %head
      %body{class: current_page.data.body_class || 'page'}
        = yield
        // jQuery
        = javascript_include_tag  "//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"
        //Here's the added update:
        = javascript_include_tag "my_jsFile" if (current_page.data.index_options == "target_file")