簡體   English   中英

包含HTML / CSS / JS文件作為代碼,而不呈現

[英]Include an HTML/CSS/JS file as code, not rendered

我有一個頁面,我正在使用ng-include將文件提取為呈現的HTML。 我想在代碼旁邊包含與代碼相同的文件。

有沒有辦法在Angular或jQuery中做到這一點? 我希望能夠將HTML,CSS和可能的JS文件包含為可以通過諸如Prism或類似工具之類的代碼渲染器運行的代碼。

這類似於jsfiddle或codepen,因為您可以在同一窗口中看到代碼和渲染視圖,但是我不需要將它們連接起來(即,編輯代碼以查看渲染結果。)我只想拉這兩個視圖來自同一文件。

我目前正在使用Angular指令遍歷JSON文件,並根據JSON中列出的內容推出HTML塊。 我的指令是:

app.directive('patterns', function() {
    return {
        restrict: 'E',
        require: ['^ngType', 'ngTemplate'],
        scope: {
            ngType: '@',
            ngTemplate: '@'
        },
        templateUrl: 'patterns.html',
        controller: function($scope, $http, $sanitize) {
            var theType = $scope.ngType;
            $http.get('indexes/json/' + theType + '.json')
                .then(function(result) {
                    $scope.patterns = result.data;
                });

        },
        controllerAs: 'patterns',
        link: function(scope, iElement, iAttrs, ctrl) {
            scope.getType(iAttrs.ngType);
        }
    }
});

而且我想添加一些也使用pattern.anchor(基於我在JSON中具有的“ anchor”鍵)的內容,以獲取特定文件並僅輸出代碼。 我目前可以將pattern.anchor與ng-include一起使用,以輸出呈現的HTML,但不僅限於代碼。

是的,使用angular可以使用ngSanitize或$ sanitize服務。

這里有一個簡單的示例: http : //codepen.io/tipsoftheday/pen/jthks

angular.module('expressionsEscaping', ['ngSanitize'])
  .controller('ExpressionsEscapingCtrl', function ($scope, $sanitize) {
      $scope.msg = 'Hello, <b>World</b>!';
      $scope.safeMsg = $sanitize($scope.msg);
});

還有一個更復雜的示例,可在以下Angular文檔中找到: https//docs.angularjs.org/api/ngSanitize/service/ $ sanitize。

&符描述的字符實體

在代碼中,將所有尖括號<>替換為字符實體代碼 &lt; &gt; 實體代碼將顯示為尖括號,但不會這樣處理。 不幸的是,這不會保留文件的格式 (請繼續閱讀以了解操作方法),因為所有空格都被壓縮為一個不間斷的空間。

 &lt;strong&gt; The strong tag is shown rather than rendered, but all whitespace characters still get compressed into a single space. However, this <br /> break tag gets rendered rather than shown. &lt;/strong&gt; 

HTML提供了一個稱為pre的塊級元素。 pre標簽內的所有內容均視為預渲染的,瀏覽器將按原樣顯示它。 此塊中的空白不會壓縮。 這將保留代碼的格式。

 <pre> &lt;strong&gt; In this block, if I add extra spaces, they are shown. If I move to a newline, that is shown as well. HTML tags still need to have<br />their angle brackets replaced in order to be shown rather than rendered.&lt;/strong&gt; </pre> 

如果使用JavaScript / AJAX包含文件,則可以首先執行字符串替換功能,以用字符實體代碼替換尖括號。 如果您正在執行服務器端包含,則可以使用您選擇的服務器端語言執行類似的操作。

如果要自動執行所有這些操作,Mike Feltman建議使用Angular的方法。

暫無
暫無

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

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