我最近在玩新的 deno 框架,一切都很棒,但在某个时候,我意识到不可能将任何额外的元数据添加到页面标题标签。基本上我想做两件事:
您知道如何实现这一目标吗?
在理想的世界中,我希望能够提供我自己的 html 模板,或者至少有一些灵活的方式来操作提供的固定模板。
我确实在 Fresh 源文件中找到了一些代码片段,它基本上是前面提到的固定 html 模板,但不幸的是它看起来对我来说不是可定制的 - 只有可变元素是 opts.headComponents,但我不确定我是否可以影响它.
export interface TemplateOptions {
bodyHtml: string;
headComponents: ComponentChildren[];
imports: (readonly [string, string])[];
styles: string[];
preloads: string[];
lang: string;
}
export function template(opts: TemplateOptions): string {
const page = (
<html lang={opts.lang}>
<head>
<meta charSet="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{opts.preloads.map((src) => <link rel="modulepreload" href={src} />)}
{opts.imports.map(([src, nonce]) => (
<script src={src} nonce={nonce} type="module"></script>
))}
<style
id="__FRSH_STYLE"
dangerouslySetInnerHTML={{ __html: opts.styles.join("\n") }}
/>
{opts.headComponents}
</head>
<body dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} />
</html>
);
return "<!DOCTYPE html>" + renderToString(page);
}
最佳答案
我在一些 fresh issue 中找到了答案. head 和 body 标签的编辑可以通过 JSX 来完成,就像这样:
/** @jsx h */
import {h} from 'preact';
import {PageProps} from '$fresh/src/server/types.ts';
import {tw} from '@twind';
export const Head = () => (
<head>
<title>My title</title>
</head>
);
export default function LoginPage(props: PageProps) {
return (
<div class={tw`w-screen h-screen flex justify-center bg-green-900`}>
<Head />
</div>
)
}
猜猜这种做事方式来自 preact 还是 SSR?从我的 Angular 来看,这有点奇怪 - 将头部/ body 注入(inject)一些 div,不是很直观。编辑
找到了更好的解决方案,因为前面给出的答案仍然导致元标记被放在正文标记内。
我们可以使用 _app.tsx ,它基本上是每个渲染路由的包装器,并使用新库中的特殊 Head 组件。这是从固定的 html 模板(有问题)填充 opts.headComponents 字段的正确方法。不幸的是,似乎没有这方面的文档。示例取自新鲜 tests :
/** @jsx h */
/** @jsxFrag Fragment */
import { Fragment, h } from "preact";
import { Head } from "$fresh/runtime.ts";
import { AppProps } from "$fresh/server.ts";
export default function App(props: AppProps) {
return (
<>
<Head>
<meta name="description" content="Hello world!" />
</Head>
<props.Component />
</>
);
}
关于javascript - Deno,Fresh 框架 - html 模板操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72889918/