将Web UI组件编译为HTML



我正在Dart web UI中构建一个简单的网站。每个页面都有一个页眉(带有站点导航)和一个页脚。我已经为页眉和页脚使用了组件,每个页面看起来像这样:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <link rel="import" href="header.html">
    <link rel="import" href="footer.html">
</head>
<body>
    <header-component></header-component>
    Page content...
    <footer-component></footer-component>
</body>
</html>

这工作得很好,但组件不是插入到HTML本身,而是从Dart(或JavaScript)代码动态加载。是否有某种方法可以让Web UI编译器将页眉和页脚插入到HTML文件本身,以便搜索引擎和禁用JavaScript的用户可以看到它们?

没有直接的方法。

这通常是一个服务器端任务:服务器负责生成所需的HTML。

Web组件都是关于客户端的,所以它们在已经交付给浏览器的内容上工作。

然而,build.dart脚本在每次项目中的文件更改时执行,因此您可以扩展脚本以获得您想要的内容。我不认为这是一个好方法,但它解决了你的问题。

首先将以下占位符添加到目标html文件中(在我的例子中是web/webuitest.html):

<header></header>

现在将header.html文件添加到您的项目中,并添加一些内容:

THIS IS A HEADER

现在扩展build.dart脚本,以便它将检查header.html是否被修改,如果是,它将更新webuitest.html:

// if build.dart arguments contain header.html in the list of changed files
if (new Options().arguments.contains('--changed=web/header.html')) {
    // read the target file
    var content = new File('web/webuitest.html').readAsStringSync();
    // read the header
    var hdr = new File('web/header.html').readAsStringSync();
    // now replace the placeholder with the header
    // NOTE: use (.|[rn])* to match the newline, as multiLine switch doesn't work as I expect
    content = content.replaceAll(
        new RegExp("<header>(.|[rn])*</header>", multiLine:true), 
        '<header>${hdr}</header>');
    // rewrite the target file with modified content
    new File('web/webuitest.html').writeAsStringSync(content);
  }

这种方法的一个后果是重写目标将再次触发build.dart,因此输出文件将构建两次,但这不是一个大问题。

当然,这可以做得更好,甚至有人可以把它包装成一个库。

目前还不可能。您需要的是这些模板的服务器端呈现,以便当客户端请求您的页面(包括搜索蜘蛛)时,您可以将它们直接提供给客户端。

您可能想要跟踪此问题:https://github.com/dart-lang/web-ui/issues/107?source=c

当它完成时,一切看起来都更好。

最新更新