📃

【Movable Type】記事一覧をjson形式で出力する

に公開

概要

記事の一覧をjson形式で出力するコードです。
以下のjsonファイルを出力します。

※ウェブページ一覧ではcategoryLabelfolderLabelにしています

[
  {
    "id": 記事ID,
    "title": "タイトル",
    "date": "日付",
    "categoryLabel": "カテゴリ(フォルダ)名",
    "description": "本文",
    "link": "記事パーマリンク"
  },
  {
    "id": 記事ID,
    "title": "タイトル",
    "date": "日付",
    "categoryLabel": "カテゴリ(フォルダ)名",
    "description": "本文",
    "link": "記事パーマリンク"
  },
  .
  .
  .
]

コード

タグの値をjsonとして扱えるよう、encode_json="1"モディファイアを付与します。
詳細は以下公式リファレンスを参照ください。

※以下のサンプルコードでは出力項目のすべてにencode_json="1"を付与していますが、jsonエンコードの必要ない項目には付与する必要はありません

MTEntriesで出力する

<mt:Entries lastn="10">
  <mt:EntriesHeader>[</mt:EntriesHeader>
  {
    "id": <$mt:EntryID$>,
    "title": "<$mt:EntryTitle encode_json='1'$>",
    "date": "<$mt:EntryDate format='%Y-%m-%d' encode_json='1'$>",
    "categoryLabel": "<mt:EntryCategories glue=","><$mt:CategoryLabel encode_json='1'$></mt:EntryCategories>",
    "description": "<$mt:EntryBody encode_json='1'$>",
    "link": "<$mt:EntryPermalink$>"
  }<mt:Unless name="__last__">,</mt:Unless>
  <mt:EntriesFooter>]</mt:EntriesFooter>
</mt:Entries>

上記は複数カテゴリが選択されることを想定したコードですが、ひとつの記事につきカテゴリをひとつしか指定しないのであれば、"categoryLabel": "<$mt:CategoryLabel encode_json='1'$>",でOKです。

MTPagesで出力する

<mt:pages lastn="10">
  <mt:SetVarBlock name="folderLabel"><mt:PageFolder><$mt:FolderLabel$></mt:PageFolder></mt:SetVarBlock>
  <mt:PagesHeader>[</mt:PagesHeader>
  {
    "id": <$mt:PageID$>,
    "title": "<$mt:PageTitle encode_json='1'$>",
    "date": "<$mt:PageDate format='%Y-%m-%d' encode_json='1'$>",
    "folderLabel": "<$mt:Var name='folderLabel' encode_json='1'$>",
    "description": "<$mt:PageBody encode_json='1'$>",
    "link": "<$mt:PagePermalink$>"
  }<mt:Unless name="__last__">,</mt:Unless>
  <mt:PagesFooter>]</mt:PagesFooter>
</mt:pages>

「ウェブページが属しているフォルダの情報」(今回であればフォルダ名)を出力する際は、いったん値を変数で定義して利用します。
詳細は以下をご参考ください。

https://zenn.dev/srkkr/articles/de578ec8f9179c

MTContentsで出力する

下記コンテンツタイプの設定を行っている想定の出力です。

  • コンテンツタイプ名:新着情報(ID: 2)
  • コンテンツフィールド
    • title:タイトル(テキスト)
    • categoryLabel:カテゴリ(カテゴリ)
    • description:本文(テキスト(複数行))
<mt:Contents content_type="2">
  <mt:ContentsHeader>[</mt:ContentsHeader>
  {
    "id": <$mt:ContentID$>,
    "title": "<mt:ContentField content_field="タイトル"><mt:ContentFieldValue encode_json='1'></mt:ContentField>",
    "date": "<mt:ContentDate format='%Y-%m-%d' encode_json='1'>",
    "categoryLabel": "<mt:ContentField content_field="カテゴリ"><mt:CategoryLabel encode_json='1'></mt:ContentField>",
    "description": "<mt:ContentField content_field="本文"><mt:ContentFieldValue encode_json='1'></mt:ContentField>",
    "link": "<$mt:ContentPermalink$>"
  }<mt:Unless name="__last__">,</mt:Unless>
  <mt:ContentsFooter>]</mt:ContentsFooter>
</mt:Contents>

上記それぞれのコードはjsonファイル出力時にMTタグ記述部分が空行で出力されるので、気になる場合はcompress-modifierプラグインを利用するなどして空行を削除してください。

以上です。

Discussion