【问题标题】:How to conditionally load / bundle CSS files in Meteor 1.0?如何在 Meteor 1.0 中有条件地加载/捆绑 CSS 文件?
【发布时间】:2015-01-31 12:21:31
【问题描述】:

我知道以前有人问过这个问题,但我想知道随着 1.0 的出现是否发生了一些变化。

我不希望 Meteor 自动将我的应用程序中的每个 CSS 文件捆绑在一起。我的管理页面将拥有与面向客户端的页面完全不同的 CSS,并且使用命名空间似乎是一个非常复杂的解决方案。如何让 Meteor 在某些页面上加载某些 CSS 文件而不在某些页面上加载某些 CSS 文件?

同样的问题也适用于 JS 文件。

我知道有人说这很有用:

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

这个包上有任何用于条件 CSS 和 JS 的 cmets 吗?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您可以将您的 CSS 文件放在 /public 下的某个位置,然后在需要的地方从模板中手动包含它们。 /public 下的所有内容都不会被捆绑,并且 URL 将删除 /public,例如

    1. 创建两个文件:your_meteor_project/public/one.css 和......./two.css。这些将可从您的客户端http://example.com/one.css 获得(即“公共”不构成 URL 的一部分,它就像使用流星作为普通旧 Web 服务器的文档根目录)。
        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. 在 HTML 的头部创建对辅助函数“适当样式表”的引用:

      HTML 模板

        <!-- 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. 创建一个辅助函数。

      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"); },
          });
    
        }
    

    你可以对 JS 文件做同样的事情。将它们放在 /public 下,流星会忽略它们。

    【讨论】:

    • 谢谢。是的,我就是这么想的。所以它不会被缩小等等。
    • 顺便说一句,您不能直接访问 Meteor 中的 。使用 jQuery 必须要有创意。
    • 真的吗? meteor docs 说你可以把东西放在&lt;head&gt; 中,它们都会被连接起来:"Meteor scans all the HTML files in your directory for three top-level elements: &lt;head&gt;, &lt;body&gt;, and &lt;template&gt;. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load." 我不是说你错了,只是文档似乎不相符。
    • 呸,你说得对。但是, 是流星不会或没有做的事情。例如,人们一直很难为 body 标签分配类。至少在之前,如果您将 body 标签放在模板中,您的应用程序会出错。
    • 恭喜,您刚刚将&lt;link type="text/css" href="{{appropriateStylesheet}}" rel="stylesheet"&gt; 添加到您的页面! @cobberboy 这就是为什么文档对此非常清楚。投反对票。
    猜你喜欢
    • 2015-01-05
    • 2017-10-30
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多