JavaScript實現模板生成大量數據的方法(附代碼)

本篇文章給大家帶來的內容是關於JavaScript實現模板生成大量數據的方法(附代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
有時需要根據模板生成大量數據,這個代碼工具簡直就是神器。

基本思路就是:

  1. 解析模板數據,將替換的內容解析出來
  2. 解析輸入數據,使用\t,\n將原始數據進行切分
  3. 進行數據替換,然後輸出。

此處用jquery實現元素的選擇,使用vue.js實現邏輯與展示的分離。

示例結果如下:
在這裏插入圖片描述

代碼如下:

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>模板生成器</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

    <script src="https://cdn.bootcss.com/vue/2.5.22/vue.min.js"></script>

 

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

 

 

    <script>

        $(document).ready(function () {

            function combineTemplateAndInput(template, input) {

                if (!template || !input) {

                    return "";

                }

                var inputLines = input.split('\n');

                var inputCount = 0;

 

                // 統計數據的數量個數

                for (var i = 0; i < inputLines.length; i++) {

                    var line = inputLines[i];

                    if (line) {

                        inputCount++;

                    }

 

                }

 

                // 替換數據

                var resLines = [];

                var inputIndex = 1;

                for (var i = 0; i < inputLines.length; i++) {

                    var line = inputLines[i];

                    // 忽略了空行

                    if (!line) {

                        resLines.push("");

                        continue;

                    }

 

                    // 將數據按\t分隔生成$1=xx,$2=xx,$3=xx

                    var dColumns = line.split('\t');

                    var mColumnData = {};

                    for (var j = 0; j < dColumns.length; j++) {

                        mColumnData['$' + (1 + j)] = dColumns[j];

                    }

 

 

                    var resLine = template;

                    // 先進行$?,$#這些替換,避免數據中的相同格式干擾

                    // 替換$?,下標

                    resLine = resLine.replace(/(\$\?)/g, inputIndex);

 

                    // 替換$#,數據數量

                    resLine = resLine.replace(/(\$#)/g, inputCount);

 

                    // 替換$0,整行數據

                    resLine = resLine.replace(/(\$0)/g, line);

 

                    // 找出模板中的`$數字`格式的內容,並進行替換

                    resLine = resLine.replace(/(\$\d+)/g, function (match, p1) {

                        if (mColumnData[p1]) {

                            return mColumnData[p1];

                        }

                        return "";

                    });

 

                    // 找出模板中`${數字}`格式的內容,進行替換

                    resLine = resLine.replace(/(\$\{\d+\})/g, function (match, p1) {

                        if (mColumnData[p1]) {

                            return mColumnData[p1];

                        }

                        return "";

                    });

 

                    inputIndex++;

 

 

                    resLines.push(resLine);

 

                }

                return resLines.join("");

            }

 

 

            var vm = new Vue({

                el: "#container",

                data: {

                    inputTemplate: [

                        "mkdir -p $4",

                        "touch $4$2.proto",

                        "\n"

                    ].join("\n"),

                    inputContent: [

                        "/abc/getNearbyOrgs/1.0    GetNearbyOrgs    GetNearbyOrgs.proto    abc/    getNearbyOrgs    /abc/getNearbyOrgs/1.0",

                        "/abc/getOrgByArea/1.0    GetOrgByArea    GetOrgByArea.proto    abc/    getOrgByArea    /abc/getOrgByArea/1.0",

                        "/abc/addFeedback/1.0    AddFeedback    AddFeedback.proto    abc/    addFeedback    /abc/addFeedback/1.0",

                        "/abc/getOrgCities/1.0    GetOrgCities    GetOrgCities.proto    abc/    getOrgCities    /abc/getOrgCities/1.0",

                        "/abc/getServiceInfo/1.0    GetServiceInfo    GetServiceInfo.proto    abc/    getServiceInfo    /abc/getServiceInfo/1.0",

                        "/hello/sayNearbyOrgs/1.0    sayNearbyOrgs    sayNearbyOrgs.proto    hello/    sayNearbyOrgs    /hello/sayNearbyOrgs/1.0",

                        "/hello/sayOrgByArea/1.0    sayOrgByArea    sayOrgByArea.proto    hello/    sayOrgByArea    /hello/sayOrgByArea/1.0",

                        "/hello/sayOrgCities/1.0    sayOrgCities    sayOrgCities.proto    hello/    sayOrgCities    /hello/sayOrgCities/1.0",

                        "/hello/sayServiceInfo/1.0    sayServiceInfo    sayServiceInfo.proto    hello/    sayServiceInfo    /hello/sayServiceInfo/1.0"

                    ].join("\n"),

                    outputContent: "",

                    msg:{

                        title:"幫助",

                        content:[

                            "$?: 數據的順序,從1開始,不含空行",

                            "$#: 數據的數量,不含空行",

                            "$0: 原始數據,整行數據",

                            "$數字: $1,$2,...,表示第1,2,...列數據",

                            "${數字}: ${11},${12},...,表示第11,12,...列數據,用於去除$11與$1的混淆(暫未實現)"

                        ].join("<br/>")

                    }

                },

                methods: {

                    aiGen: function () {

                        var self = this;

                        self.outputContent = combineTemplateAndInput(self.inputTemplate, self.inputContent);

                    },

                    clearInputContent:function () {

                        var self = this;

                        self.inputContent = "";

                    },

                    clearInputTemplate:function () {

                        var self = this;

                        self.inputTemplate = "";

                    },

                    clearOutputContent:function () {

                        var self = this;

                        self.outputContent = "";

                    }

                }

            });

 

 

        });

    </script>

</head>

<body>

 

 

<div id="container" class="container ">

 

    <div>

 

        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">

            <h3>模板生成器</h3>

        </div>

         

        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 bs-callout bs-callout-warning">

            <div class="alert alert-warning" v-html="msg.content"></div>

        </div>

        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">

 

            <div>

                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" id="inputTemplate">

                    <div>

                        <label class="col-sm-4 col-xs-4">模板</label>

                    </div>

                    <div>

                        <textarea type="text" rows="10" name="inputTemplate" id="inputTemplateText" v-model="inputTemplate"

                                  placeholder="請輸入模板"

                                 ></textarea>

                    </div>

                </div>

 

                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" id="inputContent">

                    <div>

                        <label class="col-sm-4 col-xs-4">輸入</label>

                    </div>

 

                    <div>

                        <textarea type="text" rows="10" name="inputTemplate" v-model="inputContent"

                                  placeholder="請輸入數據" id="inputContentText"

                                  class="form-control col-md-12 text-to-copy-1"></textarea>

 

                    </div>

                </div>

            </div>

        </div>

 

 

        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 text-right" id="opButtons">

            <button class="btn btn-primary" @click="clearInputTemplate()">清空模板</button>

            <button class="btn btn-primary" @click="clearInputContent()">清空輸入</button>

            <button class="btn btn-primary" @click="clearOutputContent()">清空輸出</button>

            <button class="btn btn-success" @click="aiGen()">生成</button>

        </div>

 

 

        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12" id="outputContent">

 

            <div>

                <label class="col-sm-2 col-xs-2">輸出</label>

            </div>

            <div>

                <textarea type="text" rows="20" name="outputContent" id="outputTextContent" v-model="outputContent"

                          placeholder=""

                          readonly></textarea>

            </div>

        </div>

    </div>

 

 

</div>

 

 

 

</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章