Y4NN
Y4NN

Reputation: 15

How to get a JSON response without template in eZ Publish?

I intending to get a json response without rendering a view with eZ Publish.

So I trying to use a custom module to do that:

function jsonConvert(){

     $articles = eZFunctionHandler::execute(
              'content',
              'tree',
              array(
                  'parent_node_id' => '59'
              )
          );

    header("Content-Type: application/json");

    return json_encode($articles);
  }

  echo jsonConvert();

How can I compile this module without using a basic URL that rendering a view like domain.com/module/view/ in order to get a json response without any HTML code?

Upvotes: 1

Views: 934

Answers (3)

Rey0bs
Rey0bs

Reputation: 1217

To get a blank pagelayout in your module, and set a json content type, you can add this following lines in your module php file :

header("Content-Type: application/json");
$Result = array();
$Result['content'] = json_encode($articles);
$Result['pagelayout'] = false;

Upvotes: 1

Łukasz Berwald
Łukasz Berwald

Reputation: 21

echo json_encode( YOUR ARRAY );
eZExecution::cleanExit();

It's all what you need in your custom module/view php file to return json.

Upvotes: 2

foobar
foobar

Reputation: 916

If I were you :

  1. use the builtin feature that allows you to use a different layout to render a content view. Create a new layout 'MYLAYOUT' within a layout.ini.append.php override (see https://doc.ez.no/eZ-Publish/Technical-manual/4.x/Reference/Configuration-files/layout.ini) and then call your view using /layout/set/MYLAYOUT/your/content/uri

  2. specify the content type in the layout configuration to match your requirements (application/json as the content type)

  3. create a pagelayout.tpl template used by your newly created layout which basically only contains {$module_result.content}

  4. create a template operator to convert your contents into a 'readable' json and call it from the template rendering your content (probably a /node/view/full.tpl override)

alternative (but not that sexy) to #4 => call json_encode directly in your template by allowing the php function to be called in your templates (see https://doc.ez.no/eZ-Publish/Technical-manual/4.x/Reference/Configuration-files/template.ini/PHP/PHPOperatorList)

Upvotes: 1

Related Questions