簡體   English   中英

Node.js with Express:在Jade視圖中使用腳本標簽導入客戶端javascript?

[英]Node.js with Express: Importing client-side javascript using script tags in Jade views?

我有一個運行Jade模板引擎的node.js express服務器。

我有一個布局玉文件,它導入各個視圖的主體,如下所示:

!!!
html

    head
        title= title || 'Title not set.'

    body
        #header
            h1 Header.

        #content!= body //- this renders the body of an individual view

        #footer
            p Footer.

例如,以下索引頁面:

p Welcome to the front page.

p This page serves as a now.js test.

這很好用。 但是,我現在想要專門為這個索引頁面包含兩個客戶端javascript庫(因此不是每個頁面,這就是為什么我不能把它放在布局的頭部)。

這有效:

//- import jquery
script(type='text/javascript', src='./jquery-1.5.2.min.js');

//- import now.js (hosts itself)
script(type='text/javascript', src='/nowjs/now.js')

//- import the chat client
script(type='text/javascript', src='./indexChatClient.js')

p Welcome to the front page.

p This page serves as a now.js test.

但是,這會將腳本加載到完整頁面的主體,這不是有效的HTML,對吧?

據我所知,如果我想正確地執行它,腳本應該加載到頭部,但是head部分由布局文件處理。

那么,我如何正確地包含這些客戶端javascript庫專門用於某個視圖/頁面?

您可以在布局上使用它們,並指定要在“控制器”上加載哪些庫。

// layout.jade
!!!
html

    head
        title= title || 'Title not set.'
        -each script in scripts 
          script(type='text/javascript', src= script)
    body
        #header
            h1 Header.

        #content!= body //- this renders the body of an individual view

        #footer
            p Footer.

而你的“控制器”:

// app.js
app.get('/', function (req, res) {
  res.render({
    scripts: ['jquery.min.js', '/nowjs/now.js']
  }
}

我使用這個線程的解決方案做了同樣的事情:

http://groups.google.com/group/express-js/browse_thread/thread/8c2006dc7bab37b1/f9a273c836e0a2ac

您可以在視圖選項中聲明“腳本”變量:

app.js:

app.set('view options', { locals: { scripts: ['jquery.js'] } });  // You can declare the scripts that you will need to render in EVERY page

您可以擁有一個幫助程序,將腳本標記呈現在布局的頭部

renderScriptTags()幫助程序代碼:

app.helpers({ renderScriptTags: function(scripts) {
  return scripts.map(function(script) {
    return '<script src="scripts/' + script + '"></script>';
  }).join('\n ');

進入head部分的布局模板,您將擁有:

- renderScriptTags(scripts)

現在,要在head標記上添加腳本,您只需將腳本推送到jade內容模板(body模板)上的“scripts”變量中:

- scripts.push('myscript.js'); 

通過這種方式,頁面將jquery.js和myscript.js呈現在頁面的頭部

UPDATE

似乎最新的快遞版本以不同的方式處理本地人,為了使這項工作正常,你可以這樣做(我不確定它是最佳的解決方案,但我需要稍微挖掘一下)

您可以像以前一樣在布局模板中使用上一個方法的renderScriptTags()幫助器。

但是不要將腳本變量設置為本地,而是創建一個動態幫助器,使我們的模板中的腳本變量可用:

app.dynamicHelpers({
  scripts: function(req, res){
    return ['jquery.js']; //this will be available in all views
  }
});

然后,從您的身體模板添加特定腳本(與之前完全一樣):

- scripts.push('myscript.js'); 

現在,對於這個特定的視圖,你應該正確地渲染jquery.js和myscript.js

通過將所有內容保存在模板/視圖中,可以在最新的Jade(0.28.1)中執行正確的方法(tm),而無需在其他地方黑客頁面內容(腳本鏈接):

  • 將頭部聲明為模板中的命名塊:
doctype 5
html
  head
    // named block allows us to append custom head entries in each page
    block head
        title= title
        link( rel='stylesheet', href='/css/style.css' )
        script( type="text/javascript", src="/js/some-default-script.js" )
  body
    block content
  • 在視圖中附加特定於頁面的頭元素(包括腳本標記):
extends layout

// here we reference the template head and append to it
block append head
    meta( name="something", content="blah" )
    link( href="/css/another.css", rel="stylesheet", type="text/css" )
    style
        div.foo {
            position: absolute;
        }
    script( src="/js/page-specific-script.js" )

block content
    #page-contents-follows

我假設問題(從簡要閱讀這個)是你沒有“刷新”數組,將其.length設置為0以刪除舊值,因此每個請求可能只是推動越來越多的字符串

這是另一種方法(使用ShadowCloud的答案)。 通過一般化,您可以指定本地和遠程腳本,然后將它們推遲到頁面加載之后:

app.js:

app.dynamicHelpers({
    scripts: function() {
        //scripts to load on every page
        return ['js/jquery.min.js','js/jquery-ui.min.js','js/all.js'];
    }
});

然后,您可以在視圖內的任何位置添加本地或遠程腳本

//- local script
- scripts.push('js/myPage.js');
//- remote script ( note: this is a schemeless url. You can use http(s)? ones too )
- scripts.push('//platform.twitter.com/widgets.js')

layout.jade :(我把它放在body的末尾,先加載可見的東西,但它可以去任何地方)

//- Bring the scripts into a client-side array,
//-    and attach them to the DOM one by one on page load
script
    var page_scripts = !{'["' + scripts.join('","') + '"]'};
    function loadJS() {
        for(var i in page_scripts) {
            var e = document.createElement("script");
            e.src = page_scripts[i];
            document.body.appendChild(e);
        }
    }
    // Check for browser support of event handling capability
    if (window.addEventListener)
        window.addEventListener("load", loadJS, false);
    else if (window.attachEvent)
        window.attachEvent("onload", loadJS);
    else window.onload = loadJS;

我不確定到目前為止的方法有多重要。 對我來說,做以下事情要干凈得多......

layout.jade:

doctype html
html
  head
    title= title
    block headscripts  // placeholder for scripts that need to be in the <head>
    link(rel='stylesheet', href='/styles/style.css')
    block styles       // placeholder for styles
  body
    block content
    script(src='/libs/jquery/dist/jquery.min.js') // this will render before all scripts in every page
    block scripts  // placeholder for scripts that go in the body

somepage.jade:

extends layout

block styles  // this will render in the <head>
  link(rel='stylesheet', href='/styles/films.css')
  link(rel='stylesheet', href='/styles/pagination.css')

block headscripts  // this will also render in the <head>
  script(src='/js/somescript.js')

block content
  h1= title
  div.someotherstuff

block scripts  // this will render at the end of the body
  script(src='/js/libs/someotherscript.js')
  scirpt(src='/libs/doT/doT.js')

這樣,在你的.jade頁面中放置塊的位置並不重要,它們總是在正確的位置渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM