簡體   English   中英

如何查看車把模板中的所有可用變量

[英]How to see all available variables in handlebars template

我正在開發我的第一個 Ember.js 應用程序,但在連接所有點時遇到了一些問題。 如果我能在給定的把手模板中看到所有可用的變量,那將非常有幫助。

有一個相關的問題,但您必須知道使用它的范圍內的變量: 如何在 Handlebars 模板中添加 console.log() JavaScript 邏輯?

如何輸出所有變量?

一個不錯的選擇是使用 Handlebars 助手在模板中調試 'this' 的值: 1.

{{#each}}
    {{log this}}    
{{/each}}

或者,2. 類似於@watson 建議

{{#each}}
    {{debugger}}
{{/each}}

然后在開發工具中深入到“this”的本地范圍變量

在此處輸入圖片說明

或者, 3. 您可以直接從 Controller init 方法內部記錄內容,例如:

App.UsersController = Ember.ArrayController.extend({
    init: function() {
        console.log(this);
        console.log(this.getProperties('.'));
    }
});

確保你嘗試過 Firebug - 你會從不同的角度看待事物,我發現這很有幫助。 但不要完全放棄 chrome; 在某些時候,您將需要Ember Inspector

我正在使用每個人都推薦相同調試助手,這就是 Chrome 顯示它的方式:

Chrome 檢查器不是很有幫助

當我在 firebug 中展開同一個對象時,我得到以下信息,包括我正在尋找的變量 (sources[]) 和我在 Chrome 中沒有看到的其他一些有用的屬性。

Firefox 有更多可供我使用

幾年前我創建了Barhandles 它將使用 Handlebars 解析器生成 AST,然后從中提取變量引用。 extractSchema方法將——好吧——提取一個模式。 該模式不是基於 JSON 模式或 Joi 或任何東西。 它是一種本土格式,可以捕獲您可能從 Handlebars 模板中提取的大部分內容。

所以,這個barhandlers.extractSchema('{{foo.bar}}')產生:

{
  "foo": {
    "_type": "object",
    "_optional": false,
    "bar": {
      "_type": "any",
      "_optional": false
    }
  }
}  

它將考慮到{{#if expr}}將自動使嵌套引用可選。 它根據{{#with expr}}構造正確處理范圍更改,並且還允許您添加對自己的自定義指令的支持。

我們用它來驗證我們傳遞給模板的數據結構,它為此工作得非常好。

如果您確實需要轉儲模板中的變量,則可以探索模板 AST 並輸出相關節點的內容(請參閱編譯器源代碼)。 這不是一項容易的任務,因為您必須通過試驗和錯誤找到自己的方法,而且代碼非常低級,而且沒有那么多注釋。

Handlerbars 似乎沒有您所要求的快捷方式,因此步驟是:

  1. 預編譯模板(參見命令行源代碼,我認為該函數稱為handlebars.precompile()
  2. 探索 AST

您提到的示例 Ember 應用程序在 其 app.js 中定義了其 EmberObjects。 所以基本上,對象上可用的是在那里定義的屬性。 (例如subreddit有一個title等)。

如果您想要一種全局可用的方法將對象的屬性模式轉儲到控制台,一種方法是創建一個“調試”助手,它遍歷傳入上下文的成員並將它們寫出。 就像是:

Handlebars.registerHelper('debug', function (emberObject) {
    if (emberObject && emberObject.contexts) {
        var out = '';

        for (var context in emberObject.contexts) {
            for (var prop in context) {
                out += prop + ": " + context[prop] + "\n"
            }
        }

        if (console && console.log) {
            console.log("Debug\n----------------\n" + out);
        }
    }
});

然后在任何你想檢查的地方調用它:

<div>Some markup</div>{{debug}}<div>Blah</div>

這將使用范圍內的任何 EmberObject,因此如果要檢查列表元素,而不是具有該列表的對象,則將其彈出到{{#each}}中。

您可以通過利用Handlebars.parseWithoutProcessing來執行此操作,它采用輸入模板字符串。 如果您使用 TypeScript,則返回特定類型hbs.AST.Program 您可以僅過濾 mustache 語句,然后遍歷這些語句以獲取變量名稱。

此方法還支持 Handlebars 助手,因此您可以獲取其密鑰,但正因如此,此函數有點復雜,因為您需要檢查 mustache 語句中的不同屬性:

/**
 * Getting the variables from the Handlebars template.
 * Supports helpers too.
 * @param input
 */
const getHandlebarsVariables = (input = '') => {
  const ast = Handlebars.parseWithoutProcessing(input);
  return ast.body
    .filter(({ type }) => type === 'MustacheStatement')
    .map((statement) => statement.params[0]?.original || statement.path?.original);
};

這是 TypeScript 版本,由於條件屬性,它有點復雜,但可以幫助解釋更多類型:

/**
 * Getting the variables from the Handlebars template.
 * Supports helpers too.
 * @param input
 */
const getHandlebarsVariables = (input: string): string[] => {
  const ast: hbs.AST.Program = Handlebars.parseWithoutProcessing(input);

  return ast.body.filter(({ type }: hbs.AST.Statement) => (
    type === 'MustacheStatement'
  ))
  .map((statement: hbs.AST.Statement) => {
    const moustacheStatement: hbs.AST.MustacheStatement = statement as hbs.AST.MustacheStatement;
    const paramsExpressionList = moustacheStatement.params as hbs.AST.PathExpression[];
    const pathExpression = moustacheStatement.path as hbs.AST.PathExpression;

    return paramsExpressionList[0]?.original || pathExpression.original;
  });
};

我制作了一個 Codepen 來說明這一點。 基本上,給定以下模板:

Hello, {{first_name}}! The lottery prize is {{formatCurrency prize_amount}}! Good luck!

它將使用window.prompt詢問用戶的姓名和獎金金額。 該示例還實現了一個幫助器formatCurrency 你可以在這里看到它: https : //codepen.io/tinacious/pen/GRqYWJE

在此處輸入圖片說明

模板中可用的變量僅受用於渲染模板的模型的約束。

您應該在您的應用程序中設置一個斷點,您可以在其中渲染模板並查看此時模型中的內容,這應該是您可以放入模板的內容。

暫無
暫無

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

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