1

I have a template that outputs some JSON formatted data.

I've built a simple module that needs to get the contents of that template, decode the JSON data, and return it.

I believe I need to use craft()->templates->render('path/to/template'), but when I do, I get:

Call to undefined function modules\importjsonmodule\twigextensions\craft()

The only explanation I can think of is that craft() cannot be used in a module in the way it can in a plugin. Is that the case? If so, is there any way I can access the Templates service from within a module?

Thanks

4

There is no craft() function in Craft 3 and there are no Modules in Craft 2. You probably mix the two different versions.

Craft 3

Craft::$app->getView()->renderTemplate('/path/to/template');

Of course you need to be in the correct namespace. You have to either use Craft or do \Craft

Craft 2

craft()->templates->render('path/to/template')
| improve this answer | |
  • Ah of course! Thanks @RobinSchambach. My problem now is that Craft::$app->getView()->renderTemplate appears to be setting the Content-Type header to application/json. So when I use the Twig function in a Twig template, it's trying to render the template as JSON rather than HTML. I don't suppose you know how I can stop it from doing that? – Pete H Apr 28 '18 at 18:14
  • No. The function does not change the response type at all and it does not change the headers either. When you call the function inside a template it returns normal html - like everywhere else. The response object in your Controller is responsible for the headers. If you are going to return JSON in your controller you have to to return $this->asJson($data) if not, do return $this->renderTemplate() – Robin Schambach Apr 28 '18 at 18:17
  • OK thanks @Robin. My module doesn't currently have a controller; just the main module class and the twig extension class. I think I'll need to learn a bit more about how modules work! If you don't mind, in the context of return $this->asJson($data), what is $this? – Pete H Apr 28 '18 at 18:44
  • $this is the controller that is responsible for the request. I'm still not sure what you are trying to achieve. If you want to return json in a Twig function just decode it like you are used to in PHP, if not return the html – Robin Schambach Apr 28 '18 at 18:45
  • I'm trying to create a custom twig function that gets JSON data from a template, then returns that data in a way that it can be used in the template where the twig function has been used. For example, in my HTML template, I could do {% set data = importJSON('path/to/template') %} {{ data.something }} {{ data.somethingElse }} where importJSON() is my custom twig function. – Pete H Apr 28 '18 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.