Jinja2 html representation in python 3 - html

I am writing a flask powered blog and I want to present my comments saved in XML format to the browser, so I opened the XML file and I read from it.
from xml.etree.ElementTree import parse
def blue():
with open('blogcomment.xml') as file:
doc = parse(file)
return '\n'.join("""
<div class="card">
<span></span>
<div class="content">
<p class="date">%s</p>
<h3></h3>
<p class="desc">%s</p>
</div>
</div>
"""%(item.findtext('date'), item.findtext('body')) for item in doc.iterfind('entries/entry'))
Then I called blue
#sqldb.route('/dbresult')
def dbresult():
f = blue()
return f
#Output:
11/14/2007
in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.
11/18/2007
I got the new cube I ordered. It’s a real pearl.
Which is what I wanted but I want it to be in a particular section of my blog, so I created
<!doctype html>
<html>
<head>
</head>
<body>
{{f}}
</body>
</html>
And changed my route to
#sqldb.route('/dbresult')
def dbresult():
f = blue()
return render_template('dbresult.html', f=f)
when I ran the code It Outputted
<div class="card"> <span></span> <div class="content"> <p class="date">11/14/2007</p> <h3></h3> <p
class="desc">in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</p> </div> </div> <div
class="card"> <span></span> <div class="content"> <p class="date">11/18/2007</p> <h3></h3> <p
class="desc">Got the new cube I ordered. It’s a real pearl.</p> </div> </div>
on the browser as the browser did not interpret the HTML, is it from Jinja2 or what did I do wrong I need help.
blogcomment.xml
<?xml version="1.0"?>
<blog>
<entries>
<entry>
<date>11/14/2007</date>
<name>Jeff</name>
<body>in qui latine elaboraret, ad nam phaedrum mediocrem cotidieque.</body>
</entry>
<entry>
<date>11/18/2007</date>
<name>Petter</name>
<body>Got the new cube I ordered. It’s a real pearl.</body>
</entry>
</entries>
</blog>

Flask's default configuration includes autoescaping for .html templates. Therefore when you put {{ f }} into the template the f variable is treated as an unsafe variable and any 'dangerous' character (e.g. < or >) will be escaped (converted to a HTML entity).
To prevent this behavior you can use the safe template filter, which marks the variable as safe so it will not be escaped:
<!doctype html>
<html>
<head>
</head>
<body>
{{ f | safe }}
</body>
</html>
Make sure that f does not contain any malicious code.
A better approach would be that in your blue method you just prepare the data to render (e.g. make a list of dicts from the data) and then you render the comments in a template file using the built in for control statement.

Related

Why are my Thymeleaf Path variables breaking my HTML?

I have two similar controller methods that I'm using to test the #PathVariable annotation with:
#RequestMapping(
value = "/1",
method = {RequestMethod.GET})
public String two(Model model)
{
model.addAttribute("category", "acategory");
model.addAttribute("subCategory", "placeholder");
return "homePage";
}
#RequestMapping(
path = "/{category}/{subcategory}",
method = {RequestMethod.GET})
public String three(
#PathVariable("category") String category,
#PathVariable("subcategory") String subcategory,
Model model)
{
model.addAttribute("category", "acategory");
model.addAttribute("subCategory", "placeholder");
return "homePage";
}
I would expect the exact same behavior from those two methods since I am not using the path variables passed in, and instead just hardcoding "acategory" and "placeholder". However when I navigate to localhost:8080/1 I see the content I expect but navigating to localhost:8080/asdf/asdf breaks my HTML.
Here is the HTML in question:
</head>
<body>
<div class="wrapper"> <!-- Entire page wrapper? -->
<!-- Thymeleaf fragment: commonHeader -->
<div th:replace="fragments/commonFragments :: commonHeader"></div>
<!-- Begin Page Content-->
<div th:insert="'fragments/' + ${category} :: ${subCategory}"></div>
<!-- End Page Content -->
</div> <!-- Entire page wrapper closing tag? -->
And the fragment:
<div th:fragment="placeholder">
<div class="container">
<div class="row tagline">
<div class="col-sm-12">
<p><strong>Please see page two for all related links. </strong>
<!--There's also a 3-column version of this page.--> Link to a
secondary page open accordion <a data-expand="#SecurityPanel" href="page2.html#collapse1">1</a>, <a
data-expand="#SecurityPanel" href="page2.html#collapse2">2</a>, or <a
data-expand="#SecurityPanel" href="page2.html#collapse3">3</a>.. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Vivamus hendrerit consectetur justo, vitae euismod nisl pulvinar id. In
hac habitasse platea dictumst. Nam quis ante at mi auctor vehicula. <a href="page2.html">Learn
more</a>. </p>
</div>
</div>
... more stuff cut for brevity
</div>
</div>
You probably have relative links to your CSS file, which break when you start using nested URLs. Change them to absolute links to fix it.

angularJS: template via custom directive not showing special characters

I'm trying to make my first AngularJS project and I stumbled upon a little issue...
I tried to create a custom directive (see apps.js extract) and copied some code into a separate html (see wishlist.html).
The custom directive works: the template file is included. BUT special characters like ë or € aren't shown via the custom directive and they are shown if I use the same code in the index.html.
Can somebody explain me why I get this behaviour and how to avoid it?
Thanks!
S.
index.html:
...
<body class="container" ng-app="gimmiApp">
<!-- Test with custom directive -->
<div ng-controller="WishlistController as wishlist">
<wishlist></wishlist>
</div>
<!-- Test without custom directive -->
<div ng-controller="WishlistController as wishlist">
<h1>Ideeën</h1>
<div class="row" ng-repeat="wish in wishlist.wishes">
<h3>{{wish.title}}
<em>{{wish.price | currency : "€" : 2 }}</em>
</h3>
</div>
</div>
</body>
...
wishlist.html
<h1>Ideeën</h1>
<div class="row" ng-repeat="wish in wishlist.wishes">
<h3>{{wish.title}}
<em>{{wish.price | currency : "€" : 2 }}</em>
</h3>
</div>
app.js:
...
app.directive('wishlist', function(){
return {
restrict: 'E',
templateUrl: 'views/wishlist.html'
};
});
...
This is what I get...
I found the problem!
My file wasn't encoded in UTF-8. Change my file's character set to UTF-8 solved my problem.

How to get simple text from HTML page with goquery?

I am new to Go. I am using goquery to extract data from an HTML page.
But the problem is the data I am looking for is not bounded by any HTML tag. It is simple text after a <br> tag. How can I extract it?
Edit : Here is HTML code.
<div class="container">
<div class="row">
<div class="col-lg-8">
<p align="justify"><b>Name</b>Priyaka</p>
<p align="justify"><b>Surname</b>Patil</p>
<p align="justify"><b>Adress</b><br>India,Kolhapur</p>
<p align="justify"><b>Hobbies </b><br>Playing</p>
<p align="justify"><b>Eduction</b><br>12th</p>
<p align="justify"><b>School</b><br>New Highschool</p>
</div>
</div>
</div>
From this I want "Priyanka" and "12th".
The following is what you want:
doc.Find(".container").Find("[align=\"justify\"]").Each(func(_ int, s *goquery.Selection) {
prefix := s.Find("b").Text()
result := strings.TrimPrefix(s.Text(), prefix)
println(result)
})
import strings in front of your code. If you need complete code example, check here.
Try query for and get its siblings
http://godoc.org/github.com/PuerkitoBio/goquery#Selection.Siblings

Selenium IDE Xpath vs Webdriver Xpath

I'm newbie with Test Automation. When I locating element through Firepath with target:
xpath=(//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2)
Firefox founds that element and verify text.
But, when I trying to locate this element with Visual Studio 2012 and Selenium Web driver, I constantly have error: "Unable to locate element: {"method":"xpath","selector":"//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"}" .
I tried escaping:
//td[#id=\"catProdTd_4723290\"]/div/div[2]/h2
but nothing. When I use isElementPresent method, it founds elements.
Is there some special method or rule that should be use when writing Xpath for WebDriver ?
I defined ISelenium variable, WebDriver... Clicks works, WaitForPageToLoad works, but this can not locate element.
IWebElement we= driver.FindElement(By.XPath("//td[contains(#id, 'catProdTd_4723290')]/div/div[2]/h2"));
HTML from page:
<td class="productItem" id="catProdTd_4723290"><div class="product-details">
<div class="product-aside"> <img border="0" alt="Fork and Spoon Set" src="/_photos/store/glass-large.jpg" id="catlproduct_4723290">
</div>
<div class="product-main">
<h2 class="product-name">Fork and Spoon Set</h2>
<div class="price"><strong>$17.99</strong></div>
<hr>
<div class="attributes"></div>
<hr>
<div class="product-col-1">
<div class="qty"> Quantity: <strong><input type="text" value="1" name="AddToCart_Amount" class="productTextInput" id="Units_4723290"></strong></div>
<div class="stock">(N/A in-stock)</div>
</div>
<div class="product-col-2">
<input type="submit" onclick="AddToCart(192951,4723290,'',4,'','',true);return false;" value="Buy Now" name="AddToCart_Submit" class="productSubmitInput">
<div class="wish">Add to Wishlist</div>
</div>
<div class="product-description">
<h4>Product Information:</h4>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus
</div>
</div>
<!-- End Main -->
</div>
<!-- End Product Details -->
</td>
I must add that I try to wait during debug and with
Manage().Timeouts().ImplicitlyWait
but nothing. This happens on other places also. I using Firefox for tests
You are running into dynamic attributes.
My first recommendation to you. Switch to CSS.
My second recommendation, instead of boiling down into an entire parent-child hierarchy, why don't you just KISS!
So, lets look at your issue. You are trying to fetch the product name. Easy.. we can use classes here.
css=td.productItem h2.product-name
voila, it was that easy to fetch.. instead of having this huge ugly xpath selector, we've simplified it to a css selector.
So onto the next problem, if we have multiple of td.productItem's on the page, we can use a couple things.
Try,
css=td.productItem:nth-child(1) h2.productName
That will select the first td with class, productItem.
note: you may need to specify the td's parent.. e.g. css=div#container td.productItem:nth-child(1)
More specifics...
The reason your xpath is failing, is because of that catProdTd_4723290 id assigned to the <td> element being generated automatically, rendering that element unselectable. You can work around that, by doing starts with. for example, with css -
css=td[id^='catProdTd']
will select that <td> take note though, that there might be more than 1 element selected.
I suggest using such a method for waiting:
public bool boolWaitForElementIsDisplayed(By locator, int secondsToWait)
{
WebDriverWait Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(secondsToWait));
try
{
var FoundElement = Wait.Until<Boolean>(d =>
{
try
{
return (d.FindElement(locator).Displayed && d.FindElement(locator).Enabled);
}
catch
{
return false;
}
});
}
catch (WebDriverTimeoutException)
{
return false;
}
return true;
}
and then check as follows:
IWebElement h2Element = null;
string xpath = "//td[contains(#class,'productItem')]/div/div[contains(#class,'product-main')]/h2";
if (boolWaitForElementIsDisplayed(By.XPath(xpath), 30))
h2Element = Driver.FindElement(xpath);
So, the problem was that page isn't loaded. Why? Because WebElement.Click() not works. Why Click not working?! I don't know.
I resolved problem with clicks using JavascriptExecutor:
IJavaScriptExecutor executor = (IJavaScriptExecutor)chauffeur;
IWebElement webel1 = chauffeur.FindElement(By.CssSelector("#nav ul:nth-child(1) li:nth-child(2) a[href='/products']"));
Instead of using
webel1.Click();
which not works, I used:
executor.ExecuteScript("arguments[0].click();", webel1);

Symfony2 - Get external content when rendering template

Beginner in Symfony2, so maybe it's a dumb question.
I would need to get the response of an HTTP query (external server) and put it on a template before sending it to the client.
Like
<div id="main_content">
Lorem Ipsum
<div id="external_content">
{% get_content_by_url 'http://external.com/uri' params_object %}
</div>
</div>
Or maybe I should get the response from the controller and pass it as a variable to the template ?
What is the best practice (or am I on a totaly wrong way :) ?
you can use this bundle
after enters this code in your controller:
$crawler = $client->request('GET', 'http://symfony-reloaded.org/');
$response = $client->getResponse();
$content = $response->getContent();
and finaly in file twig :
<div id="main_content">
Lorem Ipsum
<div id="external_content">
{{ content }}
</div>
</div>