Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally load / bundle CSS files in Meteor 1.0?

Tags:

meteor

I know this question has been asked before but I'm wondering if something has changed with the advent of 1.0.

I don't want Meteor to automatically bundle together every single CSS file in my app. My admin pages are going to have a completely different CSS than my client-facing pages and using namespaces seems like a really over-complicated solution. How do I have Meteor load certain CSS files on certain pages and NOT load certain CSS files on certain pages?

The same question goes for JS files.

I know someone said this would be useful:

https://github.com/anticoders/meteor-modules

Any comments on this package for conditional CSS and JS?

like image 285
fuzzybabybunny Avatar asked Oct 31 '22 13:10

fuzzybabybunny


1 Answers

You can just put your CSS files somewhere under /public and manually include them from your templates where required. Everything under /public will NOT get bundled, and the URL will have the /public removed e.g.

  1. Create two files: your_meteor_project/public/one.css and ......./two.css. These will be available from your client at http://example.com/one.css (i.e. the "public" does not form part of the URL, it's like the document root for using meteor as a plain old web server).
    meteor create cssSwitcher
    cd cssSwitcher/
    mkdir public
    echo 'html, body { background-color: red; }' > public/one.css
    echo 'html, body { background-color: blue; }' > public/two.css
  1. Create a reference to a helper function "appropriateStylesheet" in the head of your HTML :

    HTML template

    <!-- add code to the <body> of the page -->
    <body>
      <h1>Hello!</h1>
      {{> welcomePage}}
    </body>

    <!-- define a template called welcomePage -->
    <template name="welcomePage">
      <!-- add code to the <head> of the page -->
      <head>
        <title>My website!</title>
        <link rel="stylesheet" href="/{{appropriateStylesheet}}" type="text/css" />
      </head>

      <p>Welcome to my website!</p>
      <button id="red">Red</button>
      <button id="blue">Blue</button>
    </template>
  1. Create a helper function.

    JavaScript:

    if (Meteor.isClient) {
      Session.set("stylesheet","red.css"); 

      Template.registerHelper("appropriateStylesheet", function() {
        return Session.get("stylesheet");
      });

      Template.welcomePage.events({
        'click #blue' : function() { Session.set("stylesheet","two.css"); },
        'click #red'  : function() { Session.set("stylesheet","one.css"); },
      });

    }

You can do exactly the same thing with JS files. Put them under /public and meteor ignores them.

like image 90
cobberboy Avatar answered Nov 23 '22 21:11

cobberboy