Search code examples
grailsserviceviewgsp

How do I call a Grails service from a gsp?


How can I invoke a service directly from a view? I'm trying with ${my.domain.service.method}, but it complains it can't find the property.

And no, I don't want to use a controller because the view is a template.


Solution

  • <%@ page import="com.myproject.MyService" %>
    <%
        def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
    %>
    

    And then you can call ${myService.method()} in your gsp view

    Be aware that calling transactional service methods from views hurts performance. Better to move all your transactional service method calls to the controller (if you can)