jjzjj

javascript - 从组件文件和 View 模型生成原始 HTML 字符串

coder 2025-01-06 原文

我们有这样一个模板。

the-template.html

<template><div>${Foo}</div></template>

我们想用它来做这件事。

some-file.ts

let htmlString = makeItHappen('the-template.html', { Foo = 'bar' });
console.info(htmlString); // <div>bar</div>

什么是我们的 makeItHappen 函数的等价物?

最佳答案

好的,这是要点:https://gist.run/?id=d57489d279b69090fb20938bce614d3a

以下是防止丢失的代码(带有注释):

import {bindable} from 'aurelia-framework';
import {ViewLocator,ViewSlot,ViewEngine,ViewCompileInstruction} from 'aurelia-templating';
import {inject, Container} from 'aurelia-dependency-injection';

@inject(Element,ViewLocator,ViewEngine,Container)
export class LoadViewCustomAttribute {
  @bindable view;
  @bindable viewModel;

  constructor(element,vl,ve,container) {
    this.element = element;
    this.vl = vl;
    this.ve = ve;
    this.container = container;
  }

  attached() {
    // Get a view strategy for this view - this will let Aurelia know how you want to locate and load the view
    var view = this.vl.getViewStrategy(this.view);

    // Create a view factory from the view strategy (this loads the view and compiles it)
    view.loadViewFactory(this.ve, new ViewCompileInstruction()).then(vf => {
      // Create a view from the factory, passing the container (you can create a child container at this point if you want - this is what Aurelia usually does for child views) 
      var result = vf.create(this.container);
      // Bind the view to the VM - I've passed the current VM as the override context which allows Aurelia to do away with the $parent trick 
      result.bind(this.viewModel, this);

      console.log(result); // for inspection

      // Optional - create a viewslot and add the result to the DOM - 
      // at this point you have a view, you can just look at the DOM
      // fragment in the view if you want to pull out the HTML. Bear in 
      // mind, that if you do add to the ViewSlot - since nodes can only 
      // belong to 1 parent, they will be removed from the fragment in 
      // the resulting view (don't let this confuse you when debugging 
      // since Chrome shows a LIVE view of an object if you console.log(it)!) 

      // var vs = new ViewSlot(this.element, true);
      // vs.add(result);

      // Since you can't just get a fragments HTML as a string, you have to
      // create an element, add the fragment and then look at the elements innerHTML...         
      var div = document.createElement('div');
      div.appendChild(result.fragment);
      console.log(div.innerHTML);
    });
  }
}

应该这样做 - 以及用法:

<template>
  <require from="load-view"></require>
  <section>
    <div load-view="view.bind: 'view-to-load.html'; view-model.bind: { someData: 'test' }"></div>
  </section>
</template>

最后是 view-to-load.html

<template>
  <div>
    this is the template...  ${someData}
  </div>
</template>

显然,这不一定是自定义属性 - 您可以只注入(inject)位并在辅助类或类似的东西中编译(它可以只返回原始 HTML 字符串)。

这将使您的 makeItHappen 函数等效于自定义属性中的 attached 方法。当然,您需要所有的部门,所以您至少需要拥有 Aurelias 依赖注入(inject)支持才能掌握这些部门。

注意:如果您计划将内容添加到 DOM(假设您有一个可以充当 anchor 的元素),我建议始终使用 ViewSlot,因为这就是 Aurelia 的工作方式并且它会有更一致的结果,因为 ViewSlots 知道如何优雅地添加/删除孙子

如果您有一个接受字符串作为模板输入的第 3 方插件,这可能是不可能的 - 但如果可能的话,寻找与 DOM 节点一起工作的扩展点。

关于javascript - 从组件文件和 View 模型生成原始 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845208/

有关javascript - 从组件文件和 View 模型生成原始 HTML 字符串的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  9. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐