Search code examples
javascriptjquerygrails

How to load a partial template into a div in grails


I am new to grails and could not find a solution to this.

Whenever Create Client is clicked on I would like to populate the main-content div with the contents of the partial template _client.gsp.

I have the following gsp page admin.gsp

<!DOCTYPE html>
<html>
  <head>
    <title>Admin Create</title>
<meta name="layout" content="main"/>
  </head>
  <body>
    <aside class="sidebar span3">

      <ul class="nav nav-list">
        <li class="nav-header">Admin Console</li>
        <li class="create-client"><a href="#">Create Client</a></li>
        <li><a href="#">Library</a></li>
      </ul>
    </aside>

    <div class="main-content span7">
    </div>

    <g:javascript src="admin.js"/>
  </body>
</html>

I have a partial template called _client.gsp

<g:hasErrors bean="${client}">
  <div class="alert alert-error alert-block client ">
    <g:renderErrors bean="${client}" as="list" />
  </div>
</g:hasErrors>
<g:form controller="admin" action="createClient">               
  <div class="row">
    <legend>Create Client</legend>
      <div class="span4">
        <label>Client Name:</label>
        <g:textField name="client.name" />
      </div>
      <div class="span4">
        <label>Client Type:</label>
        <g:textField name="clientType.type"/>
      </div>
      <div class="span4">
        <label>External Id:</label>
        <g:field type="number" required="" min="0" value="1" name="client.externalId"/>
      </div>
    </div>
  </div>    
</g:form>

my admin.js looks like this

$(function(){
  $('.create-client').on('click', function(e){
    e.preventDefault();
    $('.create-client').addClass('active');
    $('main-content').load('_client.gsp');
  });
});

Solution

  • First, create a controller that serves up the template content for an AJAX call:

    class AdminController {
        def client() {
            render template: 'client',
                model: [...],
                contentType: 'text/plain'
    
        }
    }
    

    This renders the contents of _client.gsp as a string and returns it with a text/plain content type. In your javascript, call this with load:

    $('.main-content').load('/myapp/admin/client');