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

我正在try 构建一个服务器端MVC框架,并基于模板和诸如此类的内容生成视图,我想知道是否可以动态应用Dart的字符串插值.例如,这将是我的视图模板:

<!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变量:

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

目前这有可能吗?我对API的搜索表明并非如此.

推荐答案

(发稿:Bill Hesse)

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.

字符串插值总是动态发生的,每次文本 ,并且数据可以很容易地从函数的参数中获取 而不是脱离词汇上下文.

例如:

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);

你也可以跳过一个间接层次,直接创建

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

在需要模板的地方使用FillMyTemplate.

Dart相关问答推荐

S,返回Future.sync()的函数和不需要等待的异步函数有什么区别?

如何为屏幕设置不同的主题?

Flutter Web:无法用鼠标向下滚动(drag)(Flutter 2.5+)

Flutter.io (dart) - 如何创建左填充覆盖?

使用 Google Dart 进行数据库查询?

Flutter ToggleButton 类 - Flutter 1.9.1

当文本在 Flutter 中溢出时如何使 Text 小部件像选取框一样

Flutter中不能指定MultiPartFile的内容类型

从real mobile浏览器访问Flatter localhost

如何在Dart中switch 枚举?

Flatter BLoC-如何将参数传递给事件?

Flutter - 在 POST 请求中处理状态码 302

如何在 showModalBottomSheet 中设置状态

Dart 有小部件库吗?

一个集合如何确定两个对象在dart中相等?

对象的默认stringify,相当于Java的toString?

Dart:将十进制转换为十六进制

Dart 中的多行字符串

如何在 Dart 中定义接口?

List firstWhere Bad state: No element