我可以动态应用Dart的字符串插值吗? [英] Can I apply Dart's string interpolation dynamically?

查看:591
本文介绍了我可以动态应用Dart的字符串插值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(来自Tristan McNab的Dart讨论邮件列表)

(from the Dart discussion mailing list by Tristan McNab)

我试图构建一个服务器端mvc框架并基于模板和whatnot生成视图,我想知道是否我可以动态应用Dart的字符串插值。例如,这将是我的视图模板:

I'm trying to build a server-side mvc framework and generating views based on templates and whatnot, and I was wondering if I could apply Dart's string interpolation dynamically. For example, this would be my view template:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>${ViewData["Title"]}</title>
    <link href="/Content/css/site.css" rel="stylesheet" />
  </head>
  <body>
    <h1>${ViewData["Title"]}</h1>
    <div id="container">
      <p>Hello world!</p>
    </div>
  </body>
</html>

我想要应用ViewData变量:

And I'd like to apply the ViewData variable using:

static String applyViewData(String html, Map ViewData) {
    // apply interpolation here
}

这一切都是可能的吗?我对API的搜索表明它不是。

Is this at all possible at the moment? My searching of the APIs indicate that it isn't.

推荐答案

(由Bill Hesse发布)

(posted by Bill Hesse)

通过将字符串文字括在一个函数中,上下文为
a参数,你可以有一个Function:context - > String,你可以通过
而不是String 。如果你需要在这些对象上使用一些String
操作,比如concat,你可以在封装这个类型的类(提升)上实现这些
操作。这个
看起来像是一个简单的方法,在一个
位置给出字符串字面量,并给你想插入另一个数据。

By wrapping the string literal in a function that takes the context as a parameter, you can have a Function : context -> String that you can pass around instead of a String. If you need to use some String operations, like concat, on these objects, you can implement these operations on a class encapsulating this type ("lifting" them). This seems like a straightforward way to give the string literal in one place, and give the data you want to interpolate in another.

String插值总是动态地发生,每次使用字面值
,并且数据可以容易地从参数到函数
而不是从词汇上下文。

String interpolation always happens dynamically, each time the literal is used, and the data can easily come from a parameter to a function rather than from the lexical context.

例如:

Function MyTemplate() {
   return (Context context) {
     return "<table><tr><td class=${context.leftColumnClass}>Red Sox</td><td>${context.data}</td></tr></table>";
   }
}

...

var templateHere = MyTemplate();

...

var output = templateHere(context);

您也可以跳过间接级别并创建

You could also skip a level of indirection and just create

String FillMyTemplate(Context context) => '''
    <html><head><title>$context.title</title></head>
''';

并使用FillMyTemplate在您需要的模板。

and use FillMyTemplate where you need the template.

这篇关于我可以动态应用Dart的字符串插值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆