我需要向Docusaurus网站(基于React)上添加包含模板脚本的自定义HTML,但是该网站没有.html文件-只有.js文件,然后再编译这些文件以创建静态网站。具体来说,我需要添加一个带有<script type="text/template"></script>
块的.html文件,这意味着我不能像普通的HTML元素那样仅使用React / JSX渲染它。
到目前为止,我一直在尝试这样做,这导致文字字符串显示在页面上,其中包含我的<script type="text/template"></script>
块的内容:
Footer.js
const React = require('react');
// for instantsearch
const fs = require('fs'); //Filesystem
const resultsTemplate = fs.readFileSync(`${process.cwd()}/static/resultsTemplate.html`,"utf-8");
class Footer extends React.Component {
...
render () {
return (
<footer className='nav-footer' id='footer'>
...
{resultsTemplate}
</footer>
);
}
}
module.exports = Footer;
如果我不使用fs
而只是设置
const resultsTemplate = require(`${process.cwd()}/static/resultsTemplate.html`);
运行npm start
时出现以下错误:
(function (exports, require, module, __filename, __dirname) { <script type="text/template" id="results-template">
^
SyntaxError: Unexpected token <
这就是为什么我使用fs
的原因。
这是resultsTemplate.html
,我想添加到页脚:
<script type="text/template" id="results-template">
<div class="ais-result">
{{#hierarchy.lvl0}}
<div class="ais-lvl0">
{{{_highlightResult.hierarchy.lvl0.value}}}
</div>
{{/hierarchy.lvl0}}
<div class="ais-lvl1">
{{#hierarchy.lvl1}}
{{{_highlightResult.hierarchy.lvl1.value}}}
{{/hierarchy.lvl1}}
{{#hierarchy.lvl2}} >
...
</div>
<div class="ais-content">
{{{#content}}}
{{{_highlightResult.content.value}}}
{{{/content}}}
</div>
</div>
</script>
最后,这是应该使用正确值填充模板的功能(取自Algolia):
mainSearch.addWidget(
instantsearch.widgets.hits({
container: '#search-hits',
templates: {
empty: 'No results',
item: $('#results-template').html()
},
hitsPerPage: 10
})
);
有关更多情况,我正在尝试在我的网站中实现此功能:https://jsfiddle.net/965a4w3o/4/
答案 0 :(得分:1)
我最终找到了自己的解决方案,这在很大程度上要归功于吉安尼斯·达拉斯(Giannis Dallas)对以下问题的接受答案:add raw HTML with <script> inside Gatsby React page
解决方案:
Footer.js
const React = require('react');
// for homepage instantsearch
let resultsTemplate = `
<script type="text/template" id="results-template">
<div class="ais-result">
{{#hierarchy.lvl0}}
<div class="ais-lvl0">
{{{_highlightResult.hierarchy.lvl0.value}}}
</div>
{{/hierarchy.lvl0}}
...
</div>
<div class="ais-content">
{{{#content}}} {{{_highlightResult.content.value}}} {{{/content}}}
</div>
</div>
</script>
`
...
class Footer extends React.Component {
...
render () {
return (
<footer className='nav-footer' id='footer'>
...
<div dangerouslySetInnerHTML={{ __html: resultsTemplate }} />
</footer>
);
}
}
module.exports = Footer;
希望这可以使用类似Docusaurus或Gatsby的基于React的静态站点生成器来帮助处于类似情况的其他人!