I've noticed that the Razor <text> tag refuses to follow any formatting conventions. For example, when formatting a cshtml document, I end up with code like the following:
#MyHelper.MyMethod(#<div>
<p>Hello world</p>
</div>)
#MyHelper.MyMethod(#<text>
<p>Hello world</p>
</text>)
Note that this isn't specific to Razor template functions either, <text> blocks anywhere will do the same thing.
The client HTML tags (and their contents) such as <div> follow the formatting style I've specified, however regardless of where I add (or remove) the <text> element in the Tag Specific Options..., there is no effect. The desired result would be that the <text> element contents be formatted like the <div> element contents, in the previous example.
Are there any tricks, or work-arounds to enforcing the same formatting style on <text> elements as that of other block-level client HTML elements (<div>, <section>, etc.)
I've seen other such formatting issues with the Razor language, such as here and here, so this isn't without precedent and it seems likely there may be no solution. Either way, maybe someone has come across a fix.
It's a Razor 2.X website, building in VS 2010
Addendum
(I've grown weary of this.)
Perhaps this issue has been solved in 2012; don't know, haven't updated. However, <text> blocks, #-prefixed blocks, and more do not format well.
Another example, this time the #-prefixed blocks (constructs and such)
#foreach (var foo in bar) {
<div>#(foo.A)</div>
<div>#(foo.B)</div>
#foreach (var qux in foo.C) {
<div>#(qux.D)</div>
<div>#(qux.E)</div>
}
}
Looks more or less fine, right? Yea, unfortunately it's actually syntactically invalid. The #-prefix on the inner foreach is not permitted, as it occurs within the uninterrupted scope of an outer block (the outer foreach).
The solution? Omit the # from the inner foreach. What happens when I format?
#foreach (var foo in bar) {
<div>#(foo.A)</div>
<div>#(foo.B)</div>
foreach (var qux in foo.C) {
<div>#(qux.D)</div>
<div>#(qux.E)</div>
}
}
Awesome, lost the inner indentation. Poo.
Ok, how about those <text> blocks, they must be useful for something, right? Sure, wrap the contents of the outer foreach block in a <text> block. Now, as far as Razor is concerned, #-prefixing the inner foreach is syntactically valid.
#foreach (var foo in bar) {
<text>
<div>#(foo.A)</div>
<div>#(foo.B)</div>
#foreach (var qux in foo.C) {
<div>#(qux.D)</div>
<div>#(qux.E)</div>
}
</text>
}
Ok, fine; however, while this works it does exemplify my original question's issue. Now the <text> block contents aren't adhering to indentation. Why can't we just have:
#foreach (var foo in bar) {
<text>
<div>#(foo.A)</div>
<div>#(foo.B)</div>
#foreach (var qux in foo.C) {
<div>#(qux.D)</div>
<div>#(qux.E)</div>
}
</text>
}
Or better yet, screw the <text> block and permit #-prefixed constructs within the scope of others:
#foreach (var foo in bar) {
<div>#(foo.A)</div>
<div>#(foo.B)</div>
#foreach (var qux in foo.C) {
<div>#(qux.D)</div>
<div>#(qux.E)</div>
}
}
tl;dr
Call me anal, call me insane. Doesn't matter; so far as I can tell, this product is not working correctly, regardless of my formatting settings.
Does anyone know how to force VS 2010 Razor formatting to behave as described? (or, is this just some pipe-dream for my OCD?)
A workaround for it would be:
Right click on the cshtml file
Open with...
Choose XML (Text) Editor
Press CTRL + E, D
Related
This question already has answers here:
In which direction do selector engines read, exactly?
(2 answers)
Closed 6 years ago.
So I came across a couple of articles on CSS optimization:
http://csswizardry.com/2011/09/writing-efficient-css-selectors/
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
Apparently CSS is read from right to left. That means that div table a is read like: first all a elements on the page are retrieved, then all table elements that have an a in them (right?), then all div elements with both of those in them (right?).
My question, which I couldn't find an answer to anywhere, is: how is a CSS rule like div#div_id parsed? Do first all elements with the id "div_id" get parsed, and is a filter then applied to fetch from that bunch of #div_id elements all div elements? Or are first all div elements parsed, and is a filter then applied to fetch everything with the id "div_id"?
The first article I mentioned says that the recommended order of efficiency in CSS is: #id > > .class > tag > rest. But what about tag#id?
To clarify: I like to type div#div_id just to have it clear for myself that #div_id applies to a div element without having to look up the HTML to find out which element's styling I'm looking at, but I wouldn't want to use it that way if it costs me much of my website's performance .What would be the recommended way of writing the rule then? Should I drop the tags in my selectors? Is it really that expensive?
The answer
The answer would be, as jbutler483 says: leaving the tag name out is faster. If you want to have clarification on what element you're styling, don't use div#my_id but #div_my_id. If you don't care that much about performance, you could still go with the div#my_id, but it will be a bit slower (but you can ask yourself if it will really impact your application that much).
Ok, I think you've gotten a little confused.
In your example, you use:
div table a
So i'll use that.
Pretty much, that could look like this in your html
<div>
<table>
<a>
//styling applied here
</a>
</table>
</div>
or something else like
<div>
<div></div>
<table>
<tr>
<th>hi there</th>
<th>
<a>i'm an a tag!</a>
So, looking at that:
div table a
will be
div table a
^ ^ ^
| | |
| | a child
| |
| parent
|
grandparent
This means that you'll be styling any 'a' element that is a child/descendant of a table, which, in turn, is a descendant of a div element
so, in your other example:
div#div_id
you would be styling all id's of div_id in which have a div as a parent.
BTW looking at your example, I would like to point out that (in case you didn't know):
the id attribute should be unique
an <a> attribute shouldn't be used directly within a <table> element (instead nest it within a th or td tag)
If you wish to style multiple elements (of varying types), it would be more efficient to create a class, and use that instead
Answer after Clarification:
Your
div#div_id
In HTML, since the id is meant to be unique, it will look up 'all id's' with the specified id.
It will then check if it is a div element.
This seems to be a bad example, as obviously some (older) browsers will only look for the first id, and return it instead of checking the whole webpage for any 'duplicate' id's.
With your id's being unique, you could then drop your tag as it will be left redundant/ no use
Summary
So, an example of this extended conversation in the comments:
if I wanted to style a single div (and still know it was a div that i was adding styling to), i would use the naming convention of:
<div id="my-div-to-style">
^
|
[the word 'div' here could be anything]
in my css i would write:
_ this word must match the
/ id i used above
|
#my-div-to-style{
//styling...
}
If i wanted to add the same styling to multiple div elements (with the scope to add it to others), i would instead use a class:
<div class="myDivStyle">
and then use:
.myDivStyle{
//styling...
}
in this last example, I would not be restricted to just styling divs, so i wouldn't include this in my naming:
<div class="myStyle">
<a class="myStyle">
<table class="myStyle">
.myStyle{
//styling for any element I want
}
As you say, rules are parsed right to left, the same applies here.
Although duplicate id values are not valid, it is up to the browser to decide whether to accept and parse them, the below (in Chrome) for example, renders the first and last elements with red text.
Demo Fiddle
div#test {
color:red;
}
<div id='test'>text</div>
<span id='test'>
text
</span>
<div id='test'>text</div>
In modern browsers you may want to be less mindful of selector resolution performance and instead look to obtain valid CSS adhering to best practices, keeping selectors as short and concise as possible.
What about tag#id? The second link you mention contains the answer.
Don’t qualify ID rules with tag names or classes
If a rule has an ID selector as its key selector, don’t add the tag
name to the rule. Since IDs are unique, adding a tag name would slow
down the matching process needlessly.
Don’t qualify class rules with tag names
The previous concept also applies here. Though classes can be used
many times on the same page, they are still more unique than a tag.
You may learn more about your question here: css-tricks => efficiently rendering html
There are four kinds of key selectors: ID, class, tag, and universal. It is that same order in how efficient they are.
#main-navigation { } /* ID (Fastest) */
body.home #page-wrap { } /* ID */
.main-navigation { } /* Class */
ul li a.current { } /* Class *
ul { } /* Tag */
ul li a { } /* Tag */
* { } /* Universal (Slowest) */
#content [title='home'] /* Universal */
When we combine this right-to-left idea, and the key selector idea, we can see that this selector isn't very efficient:
#main-nav > li { } /* Slower than it might seem */
Even though that feels weirdly counter-intuitive... Since ID's are so efficient we would think the browser could just find that ID quickly and then find the li children quickly. But in reality, the relatively slow li tag selector is run first.
I need to access the value of the 10th <td> element in the last row of a table. I can't use an ID as a hook because only the table has an ID. I've managed to make it work using the code below. Unfortunately, its static. I know I will always need the 10th <td> element, but I won't ever know which row it needs to be. I just know it needs to be the last row in the table. How would I replace "tr[6]" with the actual last <tr> dynamically? (this is probably really easy, but this is literally my first time doing anything with ruby).
page = Nokogiri::HTML(open(url))
test = page.css("tr[6]").map { |row|
row.css("td[10]").text}
puts test
You want to do:
page.at("tr:last td:eq(10)")
If you do not need to do anything else with the page you can actually make this a single line with
test = Nokogiri::HTML(open(url)).search("tr").last.search("td")[10].text
Otherwise (this will work):
page = Nokogiri::HTML(open(url))
test = page.search("tr").last.search("td")[10].text
puts test
Example:(Used a large table from another question on StackOverflow)
Nokogiri::HTML(open("http://en.wikipedia.org/wiki/Richard_Dreyfuss")).search('table')[1].search('tr').last.search('td').children.map{|c| c.text}.join(" ")
#=> "2013 Paranoia Francis Cassidy"
Is there a particular reason you want an Array with 1 element? My example will return a string but you could easily modify it to return an Array.
You can use CSS pseudo class selectors for this:
page.css("table#the-table-id tr:last-of-type td:nth-of-type(10)")
This first selects the <table> with the appropriate id, then selects the last <tr> child of that table, and then selects the 10th <td> of that <tr>. The result is an array of all matching elements, if youexpect there to be only one you could use at_css instead.
If you prefer XPath, you could use this:
page.xpath("//table[#id='the-table-id']/tr[last()]/td[10]")
Here is how the html starts
BUSINESS DOCUMENTATION
<p>Some company</p>
<p>
<p>DEPARTMENT: Legal Process</p>
<p>FUNCTION: Computer Department</p>
<p>PROCESS: Process Server</p>
<p>PROCEDURE: ABC Process Server</p>
<p>OWNER: Some User</p>
<p>REVISION DATE: 06/10/2013</p>
<p>
<p>OBJECTIVE: To ensure that the process server receive their invoices the following day.</p>
<p>
<p>WHEN TO PERFORM: Daily</p>
<p>
<p>WHO WILL PERFORM? Computer Team</p>
<p>
<p>TIME TO COMPLETE: 5 minutes</p>
<p>
<p>TECHNOLOGY REQUIREMENT(S): </p>
<p>
<p>SOURCE DOCUMENT(S): N/A</p>
<p>
<p>CODES AND DEFINITIONS: N/A</p>
<p>
<table border="1">
<tr>
<td>
<p>KPI’s: </p>
</td>
</tr>
</table>
<p>
<table border="1">
<tr>
<td>
<p>RISKS: </p>
</td>
</tr>
</table>
After this there is a whole bunch of text. What I need to do is from the above I need to parse out specific data.
I need to parse out the Department, Function, Process, Procedure. Objective, When to Perform, Who Will Perform, Time To Complete, Technology Requirements, Source Documents, Codes and Definitions, Risks.
I then need to delete this information from the Html column while leaving everything else in-tact. Is this possible in LINQ?
Here is the LINQ query I am using:
var result = (from d in IPACS_Documents
join dp in IPACS_ProcedureDocs on d.DocumentID equals dp.DocumentID
join p in IPACS_Procedures on dp.ProcedureID equals p.ProcedureID
where d.DocumentID == 4
&& d.DateDeleted == null
select d.Html);
Console.WriteLine(result);
This regex worked just fine for me on your input data
(DEPARTMENT|FUNCTION|OBJECTIVE):\s*(?<value>.+)\<
The result is multiple Matches with 2 groups each - the first the key and the second the value. I have only handled two cases, but you can add the rest easily enough.
To remove the information thus parsed, you can do a Regex.Replace with this regex
(?\(DEPARTMENT|FUNCTION|OBJECTIVE):\s*)(?.+)(?\)
and replacement string as
${start}${end}
leaving out value.
In code, this looks kinda like this (quickly typed this out in Notepad++ - may have minor errors).
private static readonly ParseDocRegex = new Regex(#"(?<start>\<p\>(?<name>DEPARTMENT|FUNCTION|OBJECTIVE):\s*)(?<value>.+)(?<end>\</p\>)", RegexOptions.ExplicitCaptured | RegexOptions.Compiled);
...
from html in result
let matches = findValuesRegex.Match(html)
where matches.Success
select new
{
namesAndValues = from m in matches.AsType<Match>()
select new KeyValuePair<string, string>(m.Groups["name"].Value, m.Groups["value"].Value),
strippedHtml = ParseDocRegex.Replace(html, "${start}${end}")
};
This ought to give you the desired output.
It can be done with many LINQ statements but using regular expressions you need only a few lines of code.
For HTML, you need an HTML parser. Try HTML Agility Pack or CsQuery.
Regular expressions can handle simple matches against HTML but are not sufficient for hierarchical structures and queries would be less precise.
Any HTML extraction is going to be fragile as the structure of the HTML charges. HTML is a presentation format and creators seldom care about machine interpretation. At least with a parser, you'll get an accurate model for the presentation markup (assuming it is valid HTML). You'll also get translation of entities into characters and the ability to extract all the descendant text of an element without internal markup elements like bold or italics.
You can use arbitrary assemblies in LINQPad simply by adding a reference, and for expression-based script, you can import designated namespaces automatically.
In PHP I can do this:
<div class="foo <?php if($a) echo "bar"; ?>">
<?php if ($b) echo "</div>"; ?>
It is incredibly convenient. I can break a string in any place, between any quotes, between any HTML symbols, just wherever I want.
And I need to implement the same in Ruby-HTML. I'm trying to port a PHP project to Ruby. I use the Slim template language. I tried this but it doesn't work, Slim throws errors:
<div class="foo
- if (x == 1)
= bar
"></div>
For now with Slim I know only one way:
- if (a == true)
<div class="foo"></div>
- else
<div class="foo bar"></div>
Firstly, duplication. Secondly, my HTML-PHP part of code is quite complicated. It is with two loops (for loop and foreach loop inside it) and I use more than one such an embeds to add div's attributes according to conditions. And just cannot imagine how to implement it with Slim. It throws an error even for this, I cannot break long html string:
- if(i != 5)
<div class="foo bar"
id="item_#{i}"
style="background-color:red;"
data-im="baz">
</div>
- else
Does Slim allow to break strings with conditional ifs between quotes or element attributes? How to do it?
If you're using Rails, you're free to facilitate ActionView::Helpers this way:
= content_tag :li, class: ( a == true ? "foo bar" : "foo") do
inside div
Elsewise you're free to create some helper method to cover this logic for you
Nevertheless it's considered ill practice to include much logic in a view. Consider using some Presenter pattern
edit.
Looking into some slim docs found you're able to achieve your goal this way
div.foo class="#{'bar' if a == true}"
| Text inside div
When I use the following code in my razor view it renders <label for=""> someText</label> and not <label for="">1. someText</label> but I can't figure out why 1. is removed while rendering.
#Html.Label(String.Format("{0}. someText",1))
Edit:
The following code renders <label for="">1# someText</label> as expected.
#Html.Label(String.Format("{0}# someText",1))
You are misusing the Html.Label method. It is for:
Returns an HTML label element and the property name of the property
that is represented by the specified expression.
That's why it gets confused if you have a point . in the first parameter because it expects a property expression there.
However, you can use the second overload:
#Html.Label("", String.Format("{0}. someText",1))
Or just write out the HTML:
<label>#String.Format("{0}. someText", 1)</label>
You can avoid using the "Html Helper's label" and directly use html "label" and place whatever you want to display correctly. It can also save some time ;)
The syntax which you are using is wrong or We can say that this is not a way to use property with RAZOR syntax.
You ca use this that may be help full for you.
**
#Html.LabelFor(model => model.PropertyName,
String.Format("{0}. " + #Model.PropertyName.ToString() + ",1))
**
I was using this for a data table that contained a double (Lat/Long) and saw this same problem. Thanks for the tips (I am not allowed to comment).
For me, the problem was solved ..
#foreach (var cell in item.ItemArray)
{
<td>
#Html.Label("",cell.ToString().Trim())
</td>
}