How to work with _main.js Routing? Specially how to load specific pages?


#1

Hello.
I’m pretty new to js and jQuery, I can read most of the code but I do not understand most of the more advanced concepts.
Routing like _main.js does is completely new to me…
It does seems an amazing aproach and something I do really want to learn but as it stands now I have two doubts (only two, because I haven’t ventured a lot into it yet :stuck_out_tongue: more doubts will follow!)

  • How can I load a script based on a page template? (not based on page name or url).
  • If I load a script based on the page (for example ‘contacts’) will it work with WPML like urls (like site.com/en and site.com/it)?

Any resources you could point me to read on this topic will be welcomed (on the Routing topic :smile: )

Thank you!


#2

Did you read through the link in the file itself? https://github.com/roots/roots/blob/master/assets/js/_main.js#L3

There are also comments below the link explaining how it works.


#3

Yes I did read it.
Also read Paul Irish original post.
But still can’t figure out how to make it work based on a template file.


#4

The slug of your template file is appended to your body class. For example, if you have a template file template-home.php:

<body class="home page page-template page-template-template-home-php logged-in">

In your _main.js you can target only those pages with the assigned template:

var Roots = {
  // All pages
  common: {
    init: function() {
      // JavaScript to be fired on all pages
    }
  },
  // Template Home
  page_template_template_home_php: {
    init: function() {
      // JavaScript to be fired on the page with home template
    }
  }
};

You should convert any dashes - in the template file name to underscores _


#5

Thank you @Twansparant
This was exactly what I was looking for.

Sorry if my question was “dumb”, but I didnt got to understand it was the body classes.

Thank you @cfx too for your time.


#6

Not dumb at all! I wondered the same thing in the past and ended up using if($(’.page-template-template-name’)){} within the page: template once or twice until I figured out the correct naming convention (I’ve obviously stopped using that method!). Glad you got a quick answer.


#7

Can I add a jquery plugin inside the init calls? A plugin such as $.fn.functionname = function() {etc…}


#8

For jQuery plugins I think you should use bower.
Putting a jQuery plugin code on the routing does not seem right.