Code Spacing and Indenting Tips - spacing

I know this might spur a bit of discussion, and that isn't want this site wants, but this question CAN be answered.
I always code in one way that I am starting to frown upon:
<html>
<head>
</head>
<body>
</body>
</html>
I double space everything, and I NEVER indent, really.
Can anyone advise me on how helpful indenting and such really is? In addition, how should I indent or space if it is better for your code?
Thank you, and...
if this question is not helpful please leave a comment or suggest an edit instead of rating it down...!
EDIT: Note, this edit is after Daniel Imm's answer
How should I Indent stuff like CSS or Javascript or PHP?

Indenting means you can scan/read code much more easily basically. Start doing it and you will not know how you lived without it.
Also when you indent reading non-spaced out code is much easier. Do it like this for HTML, whenever you open a tag, make an indent:
<html>
<head>
<title></title>
</head>
<body>
<div></div>
</body>
</html>

Related

Workaround for #request.getParameters() in Thymeleaf

We are using CAS 5.2.3 which uses an upgraded version of Thymeleaf. Thymeleaf has restricted access to certain request features - '#request.getParameters()' being one. Is there any work around for it? I am getting the following error when trying to access it - "Access to request parameters is forbidden in this context. Note some restrictions apply to variable access. For example, direct access to request parameters is forbidden in preprocessing and unescaped expressions, in TEXT template mode, in fragment insertion specifications and in some specific attribute processors."
Good question. I face this problem a few months before, it is solvable.
After looking through their source code, I found that they are limiting the usage of #request.getParameters() only on specific tag, they didn't forbid to use #request.getParameters() in some situation.
In my use case, I am able to use CData to bypass this checking. Not sure whether it applies to your use case since you didn't provide any code example....
Anyway, the below example want to redirect user to another page, based on the parameter url
Here's an sample code that was broken in CAS 5.2.x, but worked in CAS 5.1.x :
<html>
<head>
<title> Deforestation </title>
</head>
<body th:attr="onload='window.location.href=\''+${#request.getParameter('url')}+'\''">
</body>
</html>
Here's a work around code:
<html>
<head>
<title> Deforestation </title>
</head>
<body>
Logging out. Please wait...
<script th:inline="javascript">
/*<![CDATA[*/
location.href = /*[[( ${#request.getParameter('url')} )]]*/ ;
/*]]>*/
</script>
</body>
</html>
If this didn't solve your problem, please provide your source code so we can have a better look at the problem.
Note: There is a security reason why this stuff is now banned, using this workaround might compromise the security standard, do remember to sanitize the user input if neccesary
Edit:
as per comment, although not elegant, maybe something like the following will work?
<html>
<head>
<title> Data attribute </title>
</head>
<body>
<span id="foobarid"> </span>
<script th:inline="javascript">
/*<![CDATA[*/
$('#foobarid').data('foo-bar',/*[[( ${#request.getParameter('foo') == 'bar'} )]]*/);
/*]]>*/
</script>
</body>
</html>
Apparently one can spend hours, even days on this simple requirement, which Thymeleaf introduced as a poorly dcumented annoyance in later versions. I've spent hours upgrading from an older Thymeleaf version from 5 years ago and got stuck on this very same problem. The lack of documentation didn't either. When I finally took a think break, I've realized the solution to this problem is as simple as using the <c:set> core tag with JSP.
Simply use the th:with tag in some higher level html tag where accessing request parameters is allowed, like this:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns="http://www.w3.org/1999/xhtml"
th:with="action=${param.action != null ?
param.action[0] : 'none'}">
<head>
...
In this example, the request parameter action is stored in a page context local variable named action (the name can be any unique name that you choose). This variable is now accessible anywhere bellow your high level html tag where you've defined it. It can even be used in following th:xx tags in the same html tag after the declaration. So basically, now you can do this:
<th:block th:switch="${action}">
<title th:case="'edit'" th:text="#{page.contacts.edit}"></title>
<title th:case="'delete'" th:text="#{page.contacts.delete}"></title>
<title th:case="*" th:text="#{page.contacts.add}"></title>
</th:block>
and even call a parameterized fragment by simply referring to your variable as ${action}. In this example I have a navbar template fragment, which accepts three parameters. The last of which, is a request parameter that otherwise, is inaccessible due to the newer Thymeleaf request object access restrictions.
<div id="wrapper">
<div class="nav" th:replace="html/fragments/navbar ::
navbar('html/contact','contact-html', ${action})">
</div>
<div class="content">
...
If you need more request params and more local page context variables, just use a comma to separate the declarations in the th:with tag like this:
th:with="action=${param.action == null ? 'none': param.action[0]},
self=${param.self == null ? 'none': param.self[0]}"
I hope this saves you guys some precious time and voids the frustration of refactoring older Thymeleaf html pages. It definitely beats those horrifically unmanageable CDATA scriptlets inside your pages.

Customizing style of html string in WKWebView

First of all let me point that I am just the beginner and that I might be missing something out, but I really need help figuring out how to get things done.
I've been able to parse xml from web address using https://github.com/tadija/AEXML parser.
Next, on WKWebView I'm using .loadHTMLString method to take only the content node of xml:
webView.loadHTMLString(xml.root["channel"]["item"]["content"].string, baseURL: nil)
Now, my webView shows the content, but I need to format the style.
I've been searching for hours now and the closest answer I could find is that i should use .css file, which makes sense and I already have custom style css file, but I can not manage to implement it. As far as I could conclude from similar questions either: in .loadHTMLString method I should use that custom css file in baseURL (if that is the case I would appreciate if someone could explain how to do it); or the answer lies in WKUserContentController with which i'm quite unfamiliar.
I would greatly appreciate any help.
Thanks a lot.
You need to link the css file into your html. If you have an external css (which I believe you have:-)) file add
<link rel="stylesheet" type="text/css" href="mystyle.css">
Alternatively you could implement an inline or internal css
JFYI
Somewhere in the head tag add
Internal css:
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
Inline css:
<h1 style="color:blue;margin-left:30px;">This is a heading.</h1>
Hope it helps you! Happy coding :)

Strange whitespace appearing in MVC4 Razor View

I'm developing an app in ASP.Net MVC4 and am having a strange issue with whitespace. I've developed plenty of MVC3 sites with Razor without this issue.
Here's my template cshtml file:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>HF - Content Management - #ViewBag.Title</title>
<link href="#Url.Content("~/content/bootstrap/bootstrap.min.css")" rel="stylesheet" />
#Styles.Render("~/bundles/css/hf-cms-logged-in")
</head>
<body>
#Html.Partial("Partials/NavBar")
<div class="container">#RenderBody()</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="#Url.Content("~/scripts/bootstrap/bootstrap.min.js")"></script>
#Scripts.Render("~/bundles/js/validation")
<script src="#Url.Content("~/scripts/hf-cms.js")"></script>
</body>
</html>
Note the line with the RenderBody() call - there's no extraneous whitespace here.
When I call an action, the rendered body is prepended with some whitespace which I can't see that I've added, and can't seem to get rid of. I call an action with no logic, it only returns the following view:
#{
ViewBag.Title = "Dashboard";
}
<h1>Dashboard</h1>
It's definitely using the correct template (specified in my _ViewStart.cshtml)
Viewing the page in Google Chrome, the source shows extra whitespace. See the image below:
A similar issue can be seen in IE10. This is obviously affecting the design. I've tried using Meleze.Web to strip out any extra whitespace, but whitespace still remains.
I'm at a loss with this one, as it's a relatively simple site so far, there's nothing funky going on yet, so I can't see where this whitespace is coming from.
Has anybody else seen this with MVC4 or Razor before?
Edit: I've tried removing all stylesheets and script files, the whitespace still exists.
After struggling with this for a while, I've found the solution.
There must have been a funny character in the root _ViewStart.cshtml file. I deleted the contents of the ViewStart file and retyped it, which solved the problem. This got me thinking that a strange character could be causing the issue.
Don't like answering my own question, but I hope this helps somebody else. In theory, this won't be an MVC4-specific issue, you could encounter the same problem in MVC3.
I encountered the same problem, and Steve's answer put me on the right track, that it might be an unusual character embedded in the file.
In my case, it turned out to be a duplicate Unicode Byte-Order Mark (0xEFBBBF) at the start of the file. It seems to have snuck in when I copied and pasted the file contents in from a Git Extensions diff view.
Incidentally, Visual Studio has a built-in Hex viewer. If you right-click on a file in the Solution Explorer and click "Open With..." you can select "Binary Editor".
I have been experiencing the same problem, and tried the approach you put forth, Steve. However, that didn't solve my problem. What I found was involved in causing the problem was the h2 tag at the top of my child page:
<h2>#ViewData("Title")</h2>
When I removed the wrapping tags, everything worked fine:
#ViewData
As a test, I took the styles for the h2 and placed them in their own class and then wrapped my page title content with a span:
<span class="pagetitle">#ViewData("Title")</span>
This worked fine, so is how I corrected the problem with my site. Though I don't know the true root cause, this did fix my problem, so perhaps it will help someone else out there.
I've just experienced a similar problem - in my case, one of the #using directives at the top of the view was causing an issue. I found the same thing in a couple of different views in my project.
One thing that helped me to locate the offending characters was pasting the whole view's contents into Notepad - it was immediately clear that the lines in question had somehow been encoded differently (they appeared smaller than the other lines, even in Notepad). Deleting the lines and rewriting them from scratch solved the issue, though I'm sadly none the wiser how I got into that position in the first place...
I have had the same issue and thanks to the clues here I was able to identify the problem.
After a lot of investigation I figured out that there was a Unicode character ‘zero width no-break space’ at the start of the page. This character is added to a page when it is saved/encoded as ‘UTF-8 with BOM’. I can only guess that the page was edited outside of visual studio, copied in from somewhere else, or maybe the page encoding was set incorrectly in VS. You stated in other answers you can see it by the looking at the once copied and pasted into notepad.
I faced the same problem, and I fixed it as follwoing:
- change column (Field) datatype in your database from nchar to nvarchar.
this is because nchar reserve fixed length, hence if your string is shorter than this length it will complete it with spaces.
I had a similar problem, but a much more obvious solution. I had an Html.Partial() inclusion in my <head> element with an ; after the method call. Which again is rendered in the body.
<head>
#await Html.PartialAsync("Test"); // The ";" is rendered in the body, remove it!
</head>
<body>
...
</body>

yield in Ruby on Rails seems to add extra space when rendering

I've got a problem with layouts and yield. When I follow the guides, I got extra space before the p tag. When I inspect the code with google chrome I got something like:
"
"
between the body and p tags. I type the same code as on the guide but it is not working, did I miss something?
Code for layout:
<html>
<head>
<title>Title</title>
</head>
<body>
<%= yield %>
</body>
</html>
and code for view:
<p>Hello, Rails!</p>
Ok, I founded the problem. It was the UTF8 encoding. In Notepad++, You have to choose to encode in UTF8 but without 'BOM', if you choose only UTF8, you get that extra character which add space.
Thanks!
You can use minus sign:
<%= yield -%>
to prevent extra space after

ASP.NET MVC 3 RAZOR Style

how to use style block in a view ?
#<Style>
...
</Style>
You have to create a RenderSection in the head of your Layout, then add section to that content in a view. See this article: http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
(Hopefully this will help the next Google visitor who gets this unanswered question first.)
style block only valid under <head> tag. if u use master page, just add content template in <head> tag
As the example:
<head>
<style>
...
</style>
</head>

Resources