Добавить HTML с шаблоном скрипта на страницу Docusaurus (React)

Мне нужно добавить собственный HTML-код, содержащий шаблонный скрипт, на сайт Docusaurus (построенный на React), но на сайте нет файлов .html - только файлы .js, которые затем компилируются для создания статического сайта. В частности, мне нужно добавить файл .html с блоком <script type = "text/template"></script>, что означает, что я не могу просто отобразить его с помощью React / JSX, как обычные элементы HTML.

Вот моя попытка сделать это до сих пор, в результате чего на странице отображается буквальная строка с содержимым моего блока <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/

🤔 А знаете ли вы, что...
React поддерживает создание анимаций и переходов между состояниями.


760
1

Ответ:

Решено

В итоге я нашел свое собственное решение, во многом благодаря принятому ответу Янниса Далласа на этот вопрос: добавить необработанный HTML с <script> на страницу Gatsby React

Решение:

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;

Надеюсь, это поможет другим в подобной ситуации, используя генераторы статических сайтов на основе React, такие как Docusaurus или Gatsby!