开发者

How can I use custom template tags inside javascript in the Play! framework?

How can I use a custom tag inside my javascript code? For example:

function toHTML(message){
    return #{customTag message:message /};
}

does not work..

Thanks!

//Some clarification

I am retrieving a list of messages using AJAX, and I have an html tag called "customTag" which contains the html code to format the message into a <li> element.

If I call

#{customTag message:'hello' /} 

directly in the HTML file, it works and replaces it by <li>hello</li>. But when I try calling it fr开发者_开发知识库om javascript, I get an error message.


The problem you have, is that you are trying to mix server-side logic (the rendering of templates) with client side events (the javascripts execution). So, your approach will not work, because the custom tag is executed from the serverside before you it ever gets to the client side.

You can get it to work using Play tags, but I would suggest that you think about using Javascript templates for doing this kind of client side. Take a look at the Chat application in the samples-and-tests folder in the Play download to see it in action. However, if you want to get it working using Play templates/tags, see below.

If you change your custom tag so that it does not take in an input, but instead is "aware" of the javascript variable, then this should work. So your tag code would look like

"<li>" +message+ "</li>";

So, this does not use the tag to pass variables into the tag, but instead uses the client side javascript variable.

I tested this with the following code in a test application (views/Application/index.html) and it outputted the javascript as expected.

<html><head></head>
<body>
<script type="text/javascript">
    function toHTML(message){
        return #{message /}
    }

    alert(toHTML("hello"));
</script>
</body>
</html>


This wont work. Try using double quotes around your value. Or, write clearly what you want actually.


In my opinion, this can't work because custom tag is evaluated on server side i.e. before the content was send to the client and then before the JavaScript was interpreted.

[sorry for my English !]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜