Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从index.html中获取一个值,并在解析JSON文件后使用它呈现第二个模板?_Javascript_Html_Json_Gulp_Pug - Fatal编程技术网

Javascript 如何从index.html中获取一个值,并在解析JSON文件后使用它呈现第二个模板?

Javascript 如何从index.html中获取一个值,并在解析JSON文件后使用它呈现第二个模板?,javascript,html,json,gulp,pug,Javascript,Html,Json,Gulp,Pug,我正试图对gulp和现代JavaScript捆绑进行思考 应用程序非常简单: 将向用户显示一个html页面,用户必须在其中选中几个单选按钮 然后,用户单击按钮提交其选择 在选择提交时,必须解析JSON文件,以便在20个可能的html页面中显示一个 我有以下(简化的)结构: dist/ index.html src/ scripts/ main.js modules/ dispatchForm.js

我正试图对
gulp
和现代JavaScript捆绑进行思考


应用程序非常简单:

  • 将向用户显示一个html页面,用户必须在其中选中几个单选按钮
  • 然后,用户单击按钮提交其选择
  • 在选择提交时,必须解析JSON文件,以便在20个可能的html页面中显示一个

  • 我有以下(简化的)结构:

    dist/
        index.html
    src/
        scripts/
              main.js
              modules/
                     dispatchForm.js
        styles/  
              index.scss
        templates/
              index.pug
              partials/
                      default.pug
                      selectors.pug
    gulpfile.js
    data.json
    

    在我的
    gulpfile.js
    中,我有:

    const bundler = () => {
      return rollup({
        input: './src/scripts/main.js',
        plugins: [
          babel(pkg.babel),
          nodeResolve(),
          commonJS(),
        ],
      }).then((bundle) => bundle.write({
        file: '.tmp/bundle.js',
        format: 'umd',
        sourceMap: 'inline',
      }));
    };
    
    const uglify = () => {
      return src('.tmp/bundle.js', {sourcemaps: true})
          .pipe(plugins.uglify())
          .pipe(dest('.tmp'))
          .pipe(plugins.size({title: 'bundler minified'}));
    };
    
    const styles = () => {
      const AUTOPREFIXER_BROWSERS = [
        'ie >= 10',
        'ie_mob >= 10',
        'ff >= 30',
        'chrome >= 34',
        'safari >= 7',
        'opera >= 23',
        'ios >= 7',
        'android >= 4.4',
        'bb >= 10',
      ];
    
      return src([
        'src/styles/main.scss',
        'src/styles/**/*.css',
      ])
          .pipe(plugins.sassGlob())
          .pipe(plugins.sass({
            precision: 10,
          }).on('error', plugins.sass.logError))
          .pipe(plugins.autoprefixer(AUTOPREFIXER_BROWSERS))
          .pipe(dest('.tmp'))
          .pipe(plugins.if('*.css', plugins.cssnano()))
          .pipe(dest('.tmp'))
          .pipe(plugins.size({title: 'styles'}));
    };
    
    // Uses PUG as template
    const templates = (env) => () => {
      return src('./src/templates/*.pug')
          .pipe(plugins.pug({locals: {
            title: pkg.title,
            description: pkg.description,
            env,
          }}))
          .pipe(dest('dist'))
          .pipe(plugins.size({title: 'templates'}));
    };
    
    const reload = (done) => {
      server.reload();
      return done();
    };
    
    
    const images = (env) => () => {
      const destination = env === 'deploy' ? 'dist' : '.tmp';
    
      return src('./src/images/**/*.{gif,jpg,png,svg}')
          .pipe(dest(destination))
          .pipe(plugins.size({title: 'size'}))
    };
    
    
    const serve = () => {
      server.init({
        notify: false,
        logPrefix: 'WSK',
        scrollElementMapping: ['main', '.mdl-layout'],
        server: ['.tmp', 'dist'],
        port: 3000,
      });
    
      watch(
        ['src/**/*.pug'],
        series(templates('development'), reload)
      );
    
      watch(
        ['src/styles/**/*.{scss,css}'],
        series(styles, templates('development'), reload)
      );
    
      watch(
        ['src/scripts/main.js', 'src/scripts/**/*.js'],
        series(bundler, templates('development'), reload)
      );
    
      watch(
        ['src/images/**/*.{gif,jpg,png,svg}'],
        series(images('development'), templates('development'), reload)
      );
    };
    
    const clean = () => del(['.tmp', 'dist/*', '!dist/.git'], {dot: true});
    
    exports.default = series(
        clean,
        bundler,
        uglify,
        styles,
        templates('deploy'),
        images('deploy')
    );
    
    exports.serve = series(
        bundler,
        styles,
        templates('development'),
        images('development'),
        serve
    );
    

    据我所知,清理文件后,捆绑程序将:

    • 从我的源代码
      main.js
      dispatchForm.js
      scss
      pug
      模板编译后,在
      dist
      文件夹中提供
      html
      页面

    Main.js

    import dispatchForm from './modules/dispatchForm';
    
    const domContentLoad = (fn) => {
      if (document.readyState !== 'loading') fn();
      else document.addEventListener('DOMContentLoaded', fn);
    };
    
    domContentLoad(() => {
      dispatchForm();
    });
    
    const button = document.querySelector('[data-calculator-button]');
    
    function updateValue() {
      const gain  = document.querySelector('[data-calculator-form][name="gain"]:checked');
      const cost  = document.querySelector('[data-calculator-form][name="cost"]:checked');
    
      if (gain && cost) {
        button.removeAttribute('disabled');
        button.classList.remove('selectors__button--inactive');
      } else {
        button.setAttribute('disabled', '');
        button.classList.add('selectors__button--inactive');
      }
    }
    
    function dispatchForm() {
      const radioInput = document.querySelectorAll('[data-calculator-form]');
      radioInput.forEach(element => element.addEventListener('input', updateValue));
    }
    
    export default dispatchForm;
    

    dispatchForm.js

    import dispatchForm from './modules/dispatchForm';
    
    const domContentLoad = (fn) => {
      if (document.readyState !== 'loading') fn();
      else document.addEventListener('DOMContentLoaded', fn);
    };
    
    domContentLoad(() => {
      dispatchForm();
    });
    
    const button = document.querySelector('[data-calculator-button]');
    
    function updateValue() {
      const gain  = document.querySelector('[data-calculator-form][name="gain"]:checked');
      const cost  = document.querySelector('[data-calculator-form][name="cost"]:checked');
    
      if (gain && cost) {
        button.removeAttribute('disabled');
        button.classList.remove('selectors__button--inactive');
      } else {
        button.setAttribute('disabled', '');
        button.classList.add('selectors__button--inactive');
      }
    }
    
    function dispatchForm() {
      const radioInput = document.querySelectorAll('[data-calculator-form]');
      radioInput.forEach(element => element.addEventListener('input', updateValue));
    }
    
    export default dispatchForm;
    

    选择器。帕格

    ...
    
    .selectors__form
        .selectors__radio
          input.selectors__input(type='radio' id='gain-points' name='gain' value='points' data-calculator-form)
          label.selectors__label(for='gain-points')
    
        .selectors__radio
          input.selectors__input(type='radio' id='gain-money' name='gain' value='money' data-calculator-form)
          label.selectors__label(for='gain-money')
    
    .selectors__form
    for value in [70, 80, 90, 100, 110, 120, 130]
      .selectors__radio
        input.selectors__input(type='radio' id=`have-${value}` name='cost' value=value data-calculator-form)
        label.selectors__label(for=`have-${value}`)
          | Até 
          b= ` C$${value}`
    
    button.selectors__button.selectors__button--calculate.selectors__button--inactive(disabled=true data-calculator-button)
    ...
    

    上面通过
    gulp
    s“bundler”从
    selectors.pug
    main.js
    dispatchForm.js
    创建一些“成本”或“收益”选择器,并将其呈现为
    html


    但现在我想:

  • 使用两个按钮提交的值(
    ${value}
    )中的一个,并将其作为参数传递给将解析
    JSON文件的函数

  • 最后,解析后的JSON结果将传递给另一个
    pug
    文件


  • 问题
  • 如何获取此JSON(从
    dispatchForm.js
    、从
    gulpfile.js
    、从
    pug
    本地获取)并将其传递给另一个
    pug
    模板

  • JSON抓取应该在单独的JS模块上处理吗,因为显示的JSON将使用另一个pug模板在单独的html页面上呈现?怎么会这样

  • 是否应该在构建时生成所有可能的第二页html文件,并使用JS仅显示基于提交值的文件?或者第二个html页面是否应该以友好方式呈现


  • 吞咽数据

    我还了解到,有一些包,如,用于处理json数据,我不知道它们是否适合这里



    此外,这还提示了如何将
    pug
    JSON
    对象传递给客户端JavaScript。

    您对这个问题的措辞让我觉得您的主要问题是将构建步骤与应用程序“运行时”(例如,当用户使用您的应用程序时)混为一谈,比如当dispatchForm.js运行时。Gulp是一个生成项目的工具,但这是在任何用户与您的站点交互之前发生的

    您链接的问题是让express在“运行时”呈现哈巴狗页面,从架构上讲,这与使用gulp在构建步骤中呈现哈巴狗页面截然不同

    如果我正确地理解了你想要什么,我有三种主要的方法。第一种方法是让客户端JS操作dom并适当地更改页面。您可以使用pug来实现这一点,通过类似(通过此找到)的方式呈现到JS库中

    第二种方法是对服务器进行api调用,然后服务器呈现一个pug模板(这就是您链接的SO问题所做的)

    或者第三,您可以做一些事情,比如渲染出您希望用户在构建时访问的所有可能的页面,然后让dispatchForm.js将它们发送到适当的页面。在本例中,我建议将这些选项定义在一个地方(比如json文件中),并将其作为一个吞咽管道的源。让gulp从一个文件生成多个文件有点滑稽,但你可以找到人们做类似事情的各种方式,如、、等等

    编辑 如果你希望事情发生在“选择提交”时,那就是方法1。因此,使用rollup插件pug,它看起来会像(完全未经测试且不在我的脑海中):

    //模块/calculateButton.js
    从“../../templates/partials/template.pug”导入templateFn;
    const button=document.querySelector(“[data calculator button]”);
    按钮。addEventListener('单击',(e)=>{
    if(如target.getAttribute('disabled'))返回;
    const gain=document.querySelector('[data calculator form][name=“gain”]:checked')。值;
    const cost=document.querySelector(“[data calculator form][name=“cost”]:选中”)。值;
    document.getElementById(“结果”).innerHTML=templateFn({
    收益、成本
    });
    });
    

    否则在提交时不会解析任何内容。对于第三种方式的例子,我建议查看我上面发送的链接。很多构建脚本只是在寻找自己的方式来完成一些事情,这些事情具有适当的能力/复杂性,并且易于维护。

    您对这个问题的表述方式让我认为您的主要问题是将构建步骤与应用程序“运行时”(例如,当用户使用您的应用程序时)混为一谈,比如运行dispatchForm.js的时候。Gulp是一个生成项目的工具,但这是在任何用户与您的站点交互之前发生的

    您链接的问题是让express在“运行时”呈现哈巴狗页面,从架构上讲,这与使用gulp在构建步骤中呈现哈巴狗页面截然不同

    如果我正确地理解了你想要什么,我有三种主要的方法。第一种方法是让客户端JS操作dom并适当地更改页面。您可以使用pug来实现这一点,通过类似(通过此找到)的方式呈现到JS库中

    第二种方法是对服务器进行api调用,然后服务器呈现一个pug模板(这就是您链接的SO问题所做的)

    第三,你可以做一些类似渲染的事情