Javascript 是否可以在PHP和JS文件中包含相同的html模板结构?

Javascript 是否可以在PHP和JS文件中包含相同的html模板结构?,javascript,php,wordpress,wordpress-theming,wordpress-rest-api,Javascript,Php,Wordpress,Wordpress Theming,Wordpress Rest Api,我正在开发一个具有一些过滤功能的网站。加载页面时,我有一个自定义的WP_查询,它加载一些摘要 <?php $recipes = new WP_Query(array( 'posts_per_page' => -1, 'post_type' => 'rezept', 'orderby' => 'menu_order' )); if ($recipes->have_posts()) { ?>

我正在开发一个具有一些过滤功能的网站。加载页面时,我有一个自定义的WP_查询,它加载一些摘要

<?php
$recipes = new WP_Query(array(
    'posts_per_page'    => -1,
    'post_type'         => 'rezept',
    'orderby'           => 'menu_order'
));

if ($recipes->have_posts()) { ?>
    <div class="results grid grid--3-col">
        <?php while ($recipes->have_posts()) {
            $recipes->the_post();
            get_template_part('template-parts/content-recipe-teaser');
        } ?>
    </div>
<?php wp_reset_postdata();
} ?>


然后,我使用过滤器菜单通过jquery.getJSON()交换摘要,而无需重新加载整个页面

this.results.hide().append(`
            ${results.recipes.map(recipe => `
                <div class="teaser teaser--recipe">
                    <a class="teaser__image" href="${recipe.permalink}">
                        <img src="${recipe.thumbnail_url}">
                    </a>
                    <a class="teaser__title" href="${recipe.permalink}">
                        <h2>${recipe.title}</h2>
                    </a>
                    <h3 class="teaser--recipe__sauce" style="color: ${recipe.sauce_color}">
                        <span
                            class="color-swatch"
                            style="background-color: ${recipe.sauce_color}">
                        </span>
                        ${recipe.sauce_name}
                    </h3>
                    <p class="teaser__text">${recipe.excerpt}</p>
                    <a href="${recipe.permalink}" class="button">
                        <span class="button__text">Zum Rezept!</a>
                    </a>
                </div>
            `).join('')}
this.results.hide().append(`
${results.recipes.map(recipe=>`
${recipe.sause_name}

${recipe.extract}

`).join(“”)}
摘要的html结构总是相同的,这就是为什么我使用get_template_part()来防止代码重复。在我的JavaScript文件中,我还需要摘要的html结构作为模板,以便通过jQuery.getJSON()动态加载所有摘要。但我当然不能使用get_template_part()在一个js文件中。有什么方法可以防止php和js文件中出现重复的模板代码吗?当需要进行更改时,在php和js中修改模板会有点乏味……你有什么建议


非常感谢!

您可以将模板存储在一个文件中,并将内容传递给JavaScript。在PHP中,您可以使用它替换
${recipe.sause\u color}
按值。或者另一种方法:在页面加载时,只向JavaScript发送数据,JavaScript呈现所有内容,不再需要PHP模板。非常感谢,我将尝试这两种方法,并找出最简单的解决方案!