[英]How can I filter frontmatter in a remark plugin?
在 AstroJS 站點中,我設置了一個備注插件,如果未明確設置,則將默認布局應用於.md(x)
文檔。 該代碼來自問題 #397中的 RFC,並且運行良好。 我現在想使用<Content/>
組件將大型文檔分解成片段。
我可以讓內容組件工作,但是每個片段都應用了默認布局,所以我在整頁中嵌套了整頁! 一種解決方案是將layout: ""
應用於我的片段,但我也在構建一個站點搜索索引,這些索引需要從中排除(因為結果將返回整頁)。 這意味着像fragment: true
這樣的自定義 frontmatter 更可取,因為它的定義更明確。
這是我目前設置的代碼:
export default function defaultLayoutPlugin() {
return function (tree, file) {
console.log(file?.data?.astro?.frontmatter);
const hasLayout = file?.data?.astro?.frontmatter?.layout;
const isFragment = file?.data?.astro?.frontmatter?.fragment ? true : false;
if (hasLayout) {
return;
}
if (isFragment) {
return;
}
// do default layout stuff
}
}
console.log
行只是為每個頁面返回undefined
,盡管它們都至少具有title
和description
屬性,如果不是也有layout
。 話雖如此,具有顯式布局的頁面並未應用默認布局,因此在某處拾取了 frontmatter,但我無法記錄它。 出於未知原因, isFragment
始終為 false,即使它明確設置為true
也是如此。
謝謝
從 Astro 版本2.0.0-beta.1
,您使用 frontmatter 的方式是正確的我用於測試示例並且我得到了這個工作。 唯一的細微差別是命名導出和未提供的配置文件。
如果您使用另一個插件注入了 frontmatter,那么請查看自 Astro 發布2.0.0-beta.0
以來的重大更改,其中指出 injectedFrontmatter the injectedFrontmatter property has been renamed to remarkPluginFrontmatter
參考https://github.com/withastro/astro/releases/tag/astro%402.0.0-beta.0
我用文件測試了你的代碼如何有和沒有這個插件的布局,類似於你剛剛調整以記錄你的 boolean 變量並找到我命名的導出導入。
function remarkLayoutCheck() {
return function transformer(syntaxTree,file) {
console.log(" --- remark Layout Check ---")
console.log(file?.data?.astro?.frontmatter);
const hasLayout = file?.data?.astro?.frontmatter?.layout;
const isFragment = file?.data?.astro?.frontmatter?.fragment ? true : false;
console.log(`hasLayout = ${hasLayout}`)
console.log(`isFragment = ${isFragment}`)
return syntaxTree;
};
}
export{
remarkLayoutCheck
}
這是 output
--- remark Layout Check ---
{ title: 'Testing Layout', layout: '../src/layouts/Layout.astro' }
hasLayout = ../src/layouts/Layout.astro
isFragment = false
--- remark Layout Check ---
{ title: 'Testing No Layout' }
hasLayout = undefined
isFragment = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.