Play2和Scala - 我的JS文件中的静态文件和I18消息

时间:2013-03-18 13:00:21

标签: javascript scala internationalization routes playframework-2.1

在我的网络应用程序中发布表单时,我在javascript中执行几项检查,然后在后端验证表单。 js验证取决于I18消息和图像。 如果这是一个scala模板,我当然会使用 @Messages @ routes.Assets.at ,但我不想混合两个(scala模板和.js)文件)。

例如我在我的js文件中检查了当前图像路径是否已硬编码:

$("form input[type=submit]").click(function (e) {

            e.preventDefault();
            var email = $("#username");
            var emailPattern = /^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;

            if (email.val() == "") {
                email.css("background-image", "url('/assets/images/general/input-row-red.jpg')");
                return e.preventDefault();
            } else {
                email.css("background-image", "url(/images/general/inputTextBg.png)");
            }
    });

我试图用他们需要的消息准备js文件,如下所示:

.js文件:

/* Prepare messages*/
var messages = "";

$.getJSON("/messages/source", {
        "keys": "sms.form.login.hide,sms.form.login"},
    function (data) {
        messages = data.messages;
    });

MessageSource控制器:

object MessageSource extends Controller {

  def getMessages(keys : String) = Action { request =>
     if(keys.isEmpty) {
       BadRequest(Json.obj("status" -> "KO", "message" -> "key plix!"))
     }
     else {
       var js = Map.empty[String, String]
       for (k <- keys.split(",")) {
         js = js + (k -> Messages(k))
       }
       Ok(Json.obj("status" -> "OK", "messages" -> js))
     }
  }
}

但我不认为这是最好的解决方案。我看过http://www.playframework.com/documentation/2.1.0/ScalaRouting,但我无法理解。 也许你有一些很好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

也许这样?

<强> jsfile:

@scripts = {
        <script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>
        <script type="text/javascript">
        jsRoutes.controllers.Application.messages("admin.venue.1,admin.venue.2,admin.venue.3" ).ajax({
            type: 'GET',
            success: function (data) {
                console.log(data.messages);

        },
            error: function () {
                console.log("error");
            }
        });
        </script>    
    }

<强>控制器:

object Application extends Controller {

  def javascriptRoutes = Action {
    implicit request =>
      import routes.javascript._
      Ok(
        Routes.javascriptRouter("jsRoutes")
          (
            routes.javascript.Application.messages
          )
      ).as("text/javascript")


  }

  def messages(keys : String) = Action {
    implicit request => {
      val messages = keys.split(",").map { key =>
        key -> Messages(key)
      }.toMap

      Ok(Json.obj("status" -> "OK", "messages" -> messages))
    }
  }

}

<强>路线:

# Javascript routes
GET         /javascriptRoutes                 controllers.Application.javascriptRoutes
GET         /messages                       controllers.Application.messages(keys: String)