Skip to content

86 craft cms之JSon

Jinxin Chen edited this page Dec 11, 2019 · 1 revision

使用前端框架的web经常会请求服务端的数据并处理,本文介绍如何在template中返回json数据

直接使用twig生成json

{% set products = craft.entries('pages')
[
  {% for page in pages %}
      {
        "title":"{{page.title}}",
        "slug":"{{page.slug}}"
      }
      {% if not loop.last %}
      ,
      {% endif %}
  {% endfor %}
]

使用插件将entities转换为json

setup plug-in

https://github.com/mattstauffer/craftcms-prune

  1. Move the prune directory into your craft/plugins directory.
  2. Go to Settings > Plugins from your Craft control panel and enable the prune plugin

usage

{{ pages | prune(['title', 'slug']) | json_encode() | raw }}
Clone this wiki locally