ForEach thymeleaf javascript - javascript

I'm trying to use thymeleaf inside javascript.
my code work fine when i use th:each with html
<table>
<tr th:each="theme : ${les_themes_1}">
<td th:text="${theme.id}">id</td>
</tr>
</table>
but when i use forEach inside a script,it return me null
<script th:inline="javascript" >
/*<![CDATA[*/
/*[# th:each="theme : ${les_themes_1}"]*/
document.write(/*[[${theme}]]*/); //return null
document.write(/*[[${theme.id}]]*/); //not working
/*[/]*/
/*]]>*/
</script>
help plz ! thank you!

This kind of question has a pretty long history, going all the way back to the early days of the JSP spec. One key thing to remember about JavaScript is that it executes within your browser based on the output generated from your server-side Java components. This is true for JSP and Javascript, Velocity and Javascript, JSTL and other custom tags and Javascript, as well as Thymeleaf and Javascript. In this scenario, the Thymeleaf template is executed well before the Javascript.
Knowing this, one critical troubleshooting strategy is to simply view and inspect the HTML & Javascript source code you generate at runtime.

Related

Value from org.springframework.ui.Model to jQuery

I'm trying to pass reCaptcha sitekey from my Spring MVC to thymeleaf template. I have an idea to reach this using jQuery $("#reCaptcha").attr("data-sitekey", reCaptchaSiteKey);, but can't find out how to get this value in jQuery.
Controller code model.addAttribute("reCaptchaSiteKey", RECAPTCHA_SITE_KEY); Would appreciate your help to solve this problem in this way or any other
There are quite a few ways to go about this. If you just want to use javascript, you can do javascript inlining:
http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
<script th:inline="javascript">
var key = [[${reCaptchaSiteKey}]];
$("#reCaptcha").attr("data-sitekey", key);
</script>
You could also use thymeleaf to directly output the #reCaptcha div
<div class="g-recaptcha" th:attr="data-sitekey=${reCaptchaSiteKey}"></div>

How to preserve c++ template code in html? [duplicate]

This question already has answers here:
How to display raw HTML code on an HTML page
(30 answers)
Closed 8 years ago.
I'm writing a C++ Style Guide for my company in html/css/javascript. I'm quite irritated with html as it treats anything between < and > as html tag and thus processes them as well. As a result of which my code (which I put in the style guide) doesn't look as such. Here is an example:
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
and I want the browser to render it exactly like that, but it doesn't render so, e.g Chrome doesn't show <std::string> part, and IE 8.0 capitalize <std::string> as <STD::STRING> (and all such template codes).
I don't want any kind of interference by html engine. Is there any simple way to achieve what I want? Any polite way to tell the browser to not modify my code?
Note that replacing < with < and > with > would work, but it is cumbersome to write it everytime I write a template code. It also makes my code difficult to read in the source code of the html. So I'm looking for a simple solution.
The notion of a "polite way to to tell the browser to not modify (parse) my code" is precisely what XML's CDATA does. Nothing more, nothing less.
CDATA does not exist in HTML, so there is no way in HTML to treat <std:vector> as anything other than on opening tag for the (non-existent) std:vector element.
The normal way to do this is a server-side transformation. Now if you aren't generating your HTML server-side, and are instead writing it by hand, you can make your life just a dash easier with a client-side transformation like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
</head>
<body>
<pre><script type="text/coffeescript" >document.write "
std::vector<std::string> get_project_names();
".replace('<','<')
</script></pre>
</body>
</html>
Here I used CoffeeScript because of its multiline string capability which is coming in ES6 for regular JavaScript. It makes it easy to just drop in your code between the boilerplate lines.
Now I know full well even this solution is lacking! If your inserted code contains a " you're out of luck. And it doesn't escape ampersands.
Bottom line is that there is no CDATA, so no "simple" solution exists. A transformation, client-side or server-side, is required.
Have you tried markdown?
I've been dealing with this particular problem for years, and it's always been frustrating. I've always appreciated the simplicity and elegance of Markdown, so I did a little research to see if there was any way to use Markdown to build an HTML document.
Thing is, code samples sometimes involve HTML, yet HTML is the language we're using to write style guides and API documentation, so my thought was that if we wrote the API documentation and style guides in Markdown, we'd eliminate all of the conflicts between HTML and the syntax of other languages.
I found Strapdown.js, which is a library that allows you to create a Web page with pure Markdown. The library then compiles it to HTML and renders it on the page client side. We put together the API documentation for one of our products using this library, and we published it as a GitHub page.
Here's a small, concise example:
<!DOCTYPE html>
<html>
<title>JavaScript API</title>
<xmp theme="united" style="display:none;">
## Print the name
Print the user's name:
```javascript
function printName(name) {
alert(name);
}
```
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
</html>
Everything inside the <xmp> tags gets compiled to HTML.
Note: The XMP tag has been deprecated for some time as per the Mozilla HTML documentation on XMP. Thus, you may want to either hack the code to make it use PRE or CODE, or you may want to consider using the lower-level Marked library that was used to build Strapdown.js. I filed an issue with the Strapdown.js team.
For that you can use this
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
This would be encoded and you'll get the result that you want.
Here is the fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/
JavaScript code
The JavaScript method of doing this would be simple, you can convert the whole code to a String variable.
As this
var string = "content here";
Then apply this,
string.replace('<','<').replace('>','>');
Convert all the characters and then have then rendered by the Browser.
http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/1/
For my book I used http://markup.su/highlighter/ syntax highlighter. Paste the code into it, generate highlighted code, and paste the latter into the HTML document. Worked pretty well. Here's a fiddle with your code: http://jsfiddle.net/6GTs2/.
Here's your code highlighted for HTML:
<pre style="background:#000;color:#f8f8f8">std::vector<std::string> <span style="color:#89bdff">get_project_names</span>();
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> Printable>
<span style="color:#99cf50">void</span> <span style="color:#89bdff">print</span>(Printable const & item);
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> FwdIterable, <span style="color:#99cf50">typename</span> Predicate>
FwdIterable <span style="color:#89bdff">find_if</span>(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>

Python and Django. Remove all js from html

I want to display user typed html (from WYSIWYG).
But I have some problems with removing js from html.
Here is my view:
def bad_view(request):
# in real project we got it from user
bad_html = '<p onclick="alert(0)">:((</p><script>alert(0);</script>'
return render(request, 'template.html', {'bad_html': bad_html})
Here code in my template:
{{ bad_html|safe }}
bad_html should be like this <p onclick="">:((</p>
What is best way to remove ALL js from this html?
For removing <script> I can use regex, but what about onclick handler(and other js handlers)?
Thanks for your advices!
I recommend using the bleach python library, it is designed to handle all sorts of special cases and be a complete solution for your problem
http://bleach.readthedocs.org/en/latest/index.html
Might I suggest a prebuilt solution for django https://www.djangopackages.com/grids/g/forms/
Most have some form of filter examples included. I am actually looking into TinyMCE myself.
More info is here Using safe filter in Django for rich text fields

Razor syntax in JavaScript code block

I want to know if it is a good practice to use razor in JavaScript code. For example:
<script type="text/javascript">
var variable = #some.Id
</script>
Or it's better to create hidden value and then take it with JavaScript, like this?
<input type="hidden" id="someId" value"#some.Id" />
<script type="text/javascript">
var variable = $('#someId').val();
</script>
EDIT:
#{
var formVariables = serializer.Serialize(new
{
id = Model.Id,
name = Model.Name,
age = Model.Age
});
<input type="hidden" id="header_variables" value="#formVariables"/>
<script type="text/javascript" src = "/Scipts/..."></script>
}
Is this good solution?
I personally would go with an extension of the 2nd option and create a seperate .js file. The reason being, if you delegate work out to a 3rd party to take care of the jquery/javascript parts of the UI, then they need not have any sight of the backend functionality.
There are a variety of ways to use html5 attributes (i.e. data-attribute='foo') on the inputs which would allow you to 'decorate' your inputs with a cargo of properties which could be parsed inside the external .js file.
A very brief example:
in your view:
<input type='text' id='myId' data-action='#Url.Action("MyAction")' class='myClass' />
in your .js file:
var targetAction = $('#myId').attr('data-action');
this gives complete separation between the .js and the views. It does require a degree of planning of course.
Hope this helps
Razor will be parsed at server-side and replaced by relevant output. Therefore, in my opinion it is totally indifferent, if you place it in Javascript or HTML - at client side only the output value will be visible. Thus, in the above example I would choose the first option (place it directly in JS), since you will not have the otherwise unnecessary hidden input field.
I don't think there is a correct answer to this question; only pros and cons.
Pros of using Razor in Javascript
Script is bound to your view model; so model changes will get picked up automatically, and errors will get caught at compile time.
Cons
Script is mixed with markup, contrary to web design best practices (put script at the bottom so that it will never break your page).
Script cannot be compiled/minified, because, again, it's mixed in with your markup.

How to merge server-side templating and AJAX to maximize reusability

Consider the following general issue before I go to the specific problem: You use server-side templating (e.g. Smarty) to generate a page in a particular way depending on a particular state. However, you can also change the state and update that page dynamically using Javascript. How do you construct such a system that does not involve replicating one's work in both Javascript and PHP?
Now, for the specific question that relates to the above. I have a navigation bar for an educational website. Depending on the URL provided by the user, you can be at various levels of navigation: field, subject, course, section, lesson. For example, if the user accesses the following index.php?field=Social_Sciences, the following XML will be returned and parsed by PHP and sent to Smarty such that the appropriate subjects are listed:
<subjects>
<subject>
<id>81</id>
<name>Sociology</name>
<description>Sociology</description>
<path>/data/material/Social_Sciences/Sociology/</path>
</subject>
<subject>
<id>82</id>
<name>Economics</name>
<description>Economics</description>
<path>/data/material/Social_Sciences/Economics/</path>
</subject>
</subject>
Similarly, if a user goes to index.php?field=Social_Sciences&subject=Economics, PHP would parse the following and send it to Smarty:
<courses>
<course>
<id>65</id>
<name>Introduction to Microeconomics</name>
<description>Introduction to Microeconomics</description>
<path>
/data/material/Social_Sciences/EconomicsIntroduction_to_Microeconomics/
</path>
</course>
<course>
<id>66</id>
<name>Introduction to Macroeconomics</name>
<description>Introduction to Macroeconomics</description>
<path>
/data/material/Social_Sciences/EconomicsIntroduction_to_Macroeconomics/
</path>
</course>
</courses>
Now, the problem is the user can also dynamically navigate using AJAX--that is, they can click through the navigation without reloading the page. That means the navigation XML then has to be parsed by jQuery, which means I have to write the same code to parse the XML twice--once in PHP and once in Javascript. After this system proved unwieldy, I started only using AJAX even on the initial load but this is sub-optimal in terms of speed and number of requests. (If you think this is trivial, there are other examples of such issues in my code.) How can one continue to use PHP templating and dynamic AJAX updating without re-writing the same parsing code twice in both languages?
JSON
If you're php actions were returning JSON objects, then I would recommend jQuery's beta product .template()
In a perfect world, you're in html 5 and can send the jQuery.template() parser equivalents of your smarty work from the server outright, as found on pandora.com's html 5 enabled player if you look at the bottom of the page source. it will kind of look like this:
<!DOCTYPE html>
<html>
<head>
<!--- pilfered from jQuery.com's demo linked above --->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#aControl").click(function(event){
$.get("/your/url").success(function(text, response, jQxhr){
$("#iWillPrintACourseTemplate").tmpl(response).appendTo("#tbodyDestination");
}).error(function(text, response, jQxhr){
});
});
});
</script>
</head>
<body>
<script id="iWillPrintACourseTemplate" type="text/x-jquery-tmpl">
<tr class="detail"><td><p>stuff : ${id} - ${}</p><p>${description}</p><p>${path}</p></td></tr>
</script>
<div><a id="aControl" href='#'>click me</a></div>
<table>
<thead/>
<tfoot/>
<tbody id="tbodyDestination">
</tbody>
</table>
</body>
</html>
not html 5
then you have to move the jQuery html 5 <script type='text/x-jquery-tmpl'/> declaration into your javascript via a $.template("name", html with templating ${} in it); i would get the html with templating ${} stuff via an ajax call. Why? I would try to keep your html templates server side. to allow easy translation between a SMARTY template and a jQuery.Template() should their syntax ever diverge.

Categories