从PrismJS代码块中的Django Template标签中删除空白

gwo2fgha  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(166)

当我在prismjs块中呈现Django模板代码时,它会去掉白色{{}}和{%%}。
例如,预呈现,代码可能是

{% image self.search_image thumbnail-400x200 as img %}
<img src="{{ img.url }}" alt="{{ img.title }}">

但呈现的代码块将是

{%image self.search_image thumbnail-400x200 as img%}
<img src="{{img.url}}" alt="{{img.title}}">

这不是css的问题,html中缺少空格。我可以将语言设置为HTML,甚至Python等,同样的问题仍然存在。
有谁知道有什么方法可以防止这种情况?

idv4meu8

idv4meu81#

PrismJS试图将您的Django模板标记处理为所选语言,我们可以告诉PrismJS忽略block, for example:中的内容
`

<pre><code class="language-none">{% image self.search_image thumbnail-400x200 as img %}
<img src="{{ img.url }}" alt="{{ img.title }}"></code></pre>

Now if we want to find a workaround for your case we could replace the spaces in your Django tags with &nbsp; before you display them in PrismJS .

`

{%&nbsp;image self.search_image thumbnail-400x200 as img&nbsp;%}
<img src="{{&nbsp;img.url&nbsp;}}" alt="{{&nbsp;img.title&nbsp;}}">
ioekq8ef

ioekq8ef2#

与其说是一个答案,不如说是一个解决方案。我添加了以下函数来将这些空格放回:

const processDjangoCodeBlock = (element) => {
    const content = element.innerHTML;

    // Step 1: Insert whitespace after "{%" and "{{" 
    //         if the next character is not whitespace
    const step1Content = content.replace(/({%)(?!\s)/g, "$1 ")
        .replace(/({{)(?!\s)/g, "$1 ");

    // Step 2: Insert whitespace before "%}" and "}}" 
    //         if the previous character is not whitespace
    const step2Content = step1Content.replace(/(?<!\s)(%})/g, " $1")
        .replace(/(?<!\s)(}})/g, " $1");

    // Update the inner HTML of the element with the processed content
    element.innerHTML = step2Content;
};

不是很满意,因为我宁愿只是停止PrismJS剥离这些摆在首位。这个问题将潜伏在核心代码的某个地方,另一个世纪,当我有更多的时间。
调用模板是一个Wagtail块,如下所示:

<pre><code class="prism-block language-{{ self.language }}" 
      id="code-block-{{ block.id }}">{{ self.code }}</code></pre>

{% if self.language == "django" %}
    <script>
    document.addEventListener("DOMContentLoaded", () => {
        setTimeout(() => {
            processDjangoCodeBlock(
                document.getElementById("code-block-{{ block.id }}")
            );
        }, 0);
    });
    </script>
{% endif %}

相关问题