Search code examples
javaspring-mvcjtwig

How to get name of the Spring project in views?


I'm using jTwig templates and i have the following one:

<!DOCTYPE HTML>
<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {% block title %}
      <title>{{ title }}</title>
    {% endblock %}

    <!-- Bootstrap stylesheet-->
    <link rel="stylesheet" href="{{webappRoot}}/apple-store/assets/css/bootstrap.min.css">

    <!-- Custom favicon -->
    <link rel="shortcut icon" href="{{webappRoot}}/apple-store/assets/img/favicon.png?v=2" />
  </head>

  <body>

    <div class="container">

         {% block content %}{% endblock %}

    </div>

    <script src="{{webappRoot}}/apple-store/assets/js/jquery-1.11.1.min.js"></script>
    <script src="{{webappRoot}}/apple-store/assets/js/bootstrap.min.js"></script>

  </body>

</html>

where apple-store is the name of my project and webappRoot is a variable from spring i think, so the full path here will be http://localhost:8080/apple-store/assets/<some asset> -- because webapp = http://localhost:8080.

There is a better way to do this? maybe a kind of "variable" like webappRoot that brings to the view the name of my project or the path http://localhost:8080/apple-store?


Solution

  • I don't know if spring has that kind of variables, i can't tell you about that, but i can tell you something kool about jTwig. It allows you to find where are your assets, how? You must have something like this:

    <beans:bean class="com.lyncode.jtwig.mvc.JtwigViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".twig" />
    </beans:bean>
    

    on your applicationContext.xml or servlet-context, in the same way you can do this:

    <beans:bean class="com.lyncode.jtwig.services.impl.assets.BaseAssetResolver">
    </beans:bean>
    

    and this is telling tou your view, that all the assets are under http://localhost/apple-store, so in your views you have to put this:

    <!-- Bootstrap stylesheet-->
    <link rel="stylesheet" href="{{ asset 'assets/css/bootstrap.min.css' }}">
    

    That's all, cheers!

    Ohh, in case if your assets aren't under assets/<url>, lets say you have your assets under public/assets/<url>, you can change your configuration like this:

    <beans:bean class="com.lyncode.jtwig.services.impl.assets.BaseAssetResolver">
        <beans:property name="prefix" value="/public/" />
    </beans:bean>