Build html tag using variable name for element - asp.net-mvc

I want to use a string variable which could contain the values h1, h2, h3 etc to build some html. This works fine for the opening tag, but does not work nicely for the closing tag. If I write
#{ var tag = "h1" ; }
<#tag>some title here</#tag>
I end up with the html
<h1>some title here</#h1>
A work-around which seems to work is
<#tag>some title here<#("/"+tag)>
but it's pretty ugly. Is there some escape sequence I need to use here?

You can use Html.Raw.
string lineTemplate = "<h{0}>{1}</h{0}>";
for (int tagCounter = 1; tagCounter < 7; tagCounter++)
{
#Html.Raw(string.Format(lineTemplate, tagCounter, "Header "+ tagCounter));
}

i am not sure which Razor version you are using
but i tested your code in my MVC4, it works perfectly
it will render <h1>something</h1>

Related

Implementing preview for markdown text

I am working on Ruby on Rails project and I have implemented markdown syntax for some text descriptions in my project using redcarpet gem.
It works like charm allowing to convert markdown text to HTML as simply as
<%= markdown some_text_variable %>
But now I want to implement preview feature rendering just small part of the full text.
The following naive construction
<%= markdown some_text_variable[0..preview_length] %>
will not work because it can easily break down MD syntax resulting in confusing constructions (imagine, for example, spliting original string on the half of image link).
I came up with
<%= markdown some_text_variable[0..preview_length].split(/\r?\n/)[0..-2].join("\r\n")) %>
but it does not deal, for example, with code blocks.
Is there any way to implement such kind of preview for MD text?
Using markdown.js and / or showdown should work. Here's a StackO with the same question and answer. I personally have used showdown in an Ember app before to render a live preview of the text as it's being typed (via 2-way data binding), and it worked flawlessly.
In the fiddle below, I wrote a little Showdown parser that takes in a string of markdown, splits it on a newline (returns an array of tags), and iterates through the array. On each iteration, it removes the tags, checks the length of the resulting string, and then compares it to the max character count for the preview. Once the next iteration surpasses the max character count, it returns the preview. The do loop ensures that you will always get at least one blob of html as a preview.
Fiddle
$(function() {
var converter = new Showdown.converter();
var previewMax = 200;
$('button').click(function() {
var content = $('#markdown').val(),
charCount = 0,
i = 0,
output = '';
if (!content) {
return $('div.preview').html("Please enter some text.");
}
var mark = converter.makeHtml(content);
var mark_arr = mark.split('\n');
while (charCount < previewMax) {
var html = mark_arr[i];
var text = htmlStrip(html);
if ((charCount + text.length) > previewMax) {
var overflow = (charCount + text.length) - previewMax;
var clipAmount = text.length - overflow;
html = jQuery.truncate(mark_arr[i], { length: clipAmount });
}
output += html;
charCount += text.length;
i++;
};
$('div.preview').html(output);
$('div.full').html(mark);
});
function htmlStrip (html) {
var div = document.createElement('div');
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
return text;
}
});
REVISION
I updated the function using jQuery Truncate to cut the final string into an elipses so that all your previews are the same length as the others. Also, I realized that the original function returned a long string of undefined' over and over when no text was entered, so there is a check to eliminate that. Since this loop will always return at least one html item now, I changed the do loop to a while loop for easier reading. Finally, if you want your truncation to always end at a word boundary, pass the words: true option when you call it. Obviously, this will not give you the same level of truncation for every preview, but it will improve legibility. That's it!
I want to share my preview version it was quite simple with showdown.js and prism.js syntax highlighting.
Prism.js is syntaxing easily with JavaScript and CSS. All you need to pick specific languages and download it to assets folder. Or you can specify it to specific pages.
This is going to happen in realtime preview, in a form.
In Rails form:
<div class="col-md-12">
<div class="form-group">
<%= f.label :body %>
<%= f.text_area :body, class: "form-control", rows: 10 %>
</div>
</div>
<div class="col-md-12">
<h1> Preview Markdown </h1>
<div class="form-group markdownOutput"></div>
</div>
And add this script right below a form page.
<script>
function mkdown(){
var converter = new showdown.Converter(),
$post_body = $("#post_body");
// This line will keep adding new rows for textarea.
function postBodyLengthDetector(post_body){
var lines = post_body.val().split("\n");
post_body.prop('rows', lines.length+5);
}
// Textarea rows in default '10', when focusing on this. It will expand.
$post_body.focus(function(){
postBodyLengthDetector($(this));
$('.markdownOutput').html(converter.makeHtml($post_body.val()));
});
// All simple magic goes here, each time when texting anything into textarea
//it will be generated to markdown. You are able to see preview right below of textarea.
$post_body.keyup(function() {
postBodyLengthDetector($(this));
var value = $( this ).val(),
html = converter.makeHtml(value);
$('.markdownOutput').html(html);
});
}
$(mkdown);
$(document).on("turbolinks:load", mkdown);
</script>

set maxlength in textarea

I want to set maxlength in textarea. I have defined maxlength property in textarea but it seems to be of no use. Pls help. My code:
<html:textarea styleClass="textarea" maxlength="2100" cols="60" rows="3">
Try this javascript function:
$(function(){
$("#id").keypress(function() {
var maxlen = 100; //length as you desire
if ($(this).val().length > maxlen) {
return false;
}
})
});
You have to write code for two events, keyup and copy paste so try this:
onKeyPress = "return ( this.value.length < 2100 );", onPaste = "return onTextAreaPaste(this,2100)"
Here is Js:
function onTextAreaPaste(textArea,size) {
var length = textArea.value.length;
if(window.clipboardData!=undefined)
length = textArea.value.length + window.clipboardData.getData('Text').length;
return length < size;
}
I recently came across a problem with textarea maxlength attribute because the newlines where considered as 1 in Firefox, and 2 in IE and Chrome. So I decide to go for JavaScript for handling this.
Here is how I handle the max length, its a jquery plugin, very easy to set and there's no problem with the different behaviors of browsers, plus give you a feedback of the characters used.

Prevent CKEditor filtering Radiant Tags (non-valid HTML tags)

I'm using CKEditor with refinerycms (rails CMS) I've also added basic support for radius tags (they are the tags used in Radiant, another rails CMS) so I'm able to list some elements from the model in the page just inserting a code.
The problem is that the radius tags mimic html:
<r:product_listing category="products" list_as="grid"/>
When using CKEditor to modify the page contents it thinks the radius tags are invalid HTML, which is correct and the expected behaviour, but I can't find the way to tell CKEditor to just ignore those tags.
Any ideas?
Thanks in advance
EDIT: Turned out that the tag was being filtered by the sanitize method in rails being called by RefineryCMS.
What kind of issues do you have with custom tags? And on which browsers?
I checked that CKEditor preserves this tag, but wraps entire content with it. To avoid that you have to edit CKEDITOR.dtd, namely:
CKEDITOR.dtd.$empty[ 'r:product_listing' ] = 1;
But that still may not be enough. To have better support you'd need to make more changes in this object - especially important is to define what can be its parents and that it's an inline tag. For example:
CKEDITOR.dtd.p[ 'r:product_listing' ] = 1; // it is allowed in <p> tag
CKEDITOR.dtd.$inline[ 'r:product_listing' ] = 1;
This still may not be enough - for example you'll most likely won't have copy&paste support.
So, if you need more reliable support I'd try a little bit different way. Using CKEDITOR.dataProcessor you can transform this tag into some normal one when data are loaded into editor and when data are retrieved transform it back to that tag.
Example solution:
// We still need this, because this tag has to be parsed correctly.
CKEDITOR.dtd.p[ 'r:product_listing' ] = 1;
CKEDITOR.dtd.$inline[ 'r:product_listing' ] = 1;
CKEDITOR.dtd.$empty[ 'r:product_listing' ] = 1;
CKEDITOR.replace( 'editor1', {
on: {
instanceReady: function( evt ) {
var editor = evt.editor;
// Add filter for html->data transformation.
editor.dataProcessor.dataFilter.addRules( {
elements: {
'r:product_listing': function( element ) {
// Span isn't self closing element - change that.
element.isEmpty = false;
// Save original element name in data-saved-name attribute.
element.attributes[ 'data-saved-name' ] = element.name;
// Change name to span.
element.name = 'span';
// Push zero width space, because empty span would be removed.
element.children.push( new CKEDITOR.htmlParser.text( '\u200b' ) );
}
}
} );
// Add filter for data->html transformation.
editor.dataProcessor.htmlFilter.addRules( {
elements: {
span: function( element ) {
// Restore everything.
if ( element.attributes[ 'data-saved-name' ] ) {
element.isEmpty = true;
element.children = [];
element.name = element.attributes[ 'data-saved-name' ];
delete element.attributes[ 'data-saved-name' ]
}
}
}
} );
}
}
} );
Now r:product_listing element will be transformed into span with zero-width space inside. Inside editor there will be a normal span, but in source mode and in data got by editor#getData() method you'll see original r:product_listing tag.
I think that this solution should be the safest one. E.g. copy and pasting works.
u can also add as protected source, so no filtering or parsing will be done.
config.protectedSource.push(/<r:product_listing[\s\S]*?\/>/g);
just add these line to your config.js ([\s\S]*? is for any random content)
check out http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-protectedSource

Getting cleaned HTML in text from HtmlCleaner

I want to see the cleaned HTML that we get from HTMLCleaner.
I see there is a method called serialize on TagNode, however don't know how to use it.
Does anybody have any sample code for it?
Thanks
Nayn
Here's the sample code:
HtmlCleaner htmlCleaner = new HtmlCleaner();
TagNode root = htmlCleaner.clean(url);
HtmlCleaner.getInnerHtml(root);
String html = "<" + root.getName() + ">" + htmlCleaner.getInnerHtml(root) + "</" + root.getName() + ">";
Use a subclass of org.htmlcleaner.XmlSerializer, for example:
// get the element you want to serialize
HtmlCleaner cleaner = new HtmlCleaner();
TagNode rootTagNode = cleaner.clean(url);
// set up properties for the serializer (optional, see online docs)
CleanerProperties cleanerProperties = cleaner.getProperties();
cleanerProperties.setOmitXmlDeclaration(true);
// use the getAsString method on an XmlSerializer class
XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
String html = xmlSerializer.getAsString(rootTagNode);
XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
String html = xmlSerializer.getAsString(rootTagNode);
the method above has a problem,it will trim content in html label, for example,
this is paragraph1.
will become
this is paragraph1.
and it is getSingleLineOfChildren function does the trim operation. So if we fetch data from website and want to keep the format like tuckunder.
PS:if a html label has children label,the parent label contetn will not be trimed,
for example <p> this is paragraph1. <a>www.xxxxx.com</a> </p> will keep whitespace before "this is paragraph1"

ASP.NET MVC Razor extra whitespace rendered

In Asp.net MVC, Razor inserts extra space between text blocks. I want to render a list this way: "1, 2, 3" but get "1 , 2 , 3".
#for (int i = 1; i < 3; i++)
{
<text>#i</text>
if (i != 2)
{
<text>, </text>
}
}
Is there any ways to remove extra whitespace ?
I want to render a list this way: "1, 2, 3"
Quick and dirty:
#string.Join(", ", Enumerable.Range(1, 3))
Obviously a custom helper seems more appropriate to the job of formatting something in the view:
public static class HtmlExtensions
{
public static IHtmlString FormatList(this HtmlHelper html, IEnumerable<int> list)
{
return MvcHtmlString.Create(string.Join(", ", list));
}
}
and then simply:
#Html.FormatList(Model.MyList)
You are seeing the extra whitespace between the number and the comma because your razor template includes a line break (which displays as whitespace in the browser) between the number and the comma:
#for (int i = 1; i < 3; i++)
{
<text>#i</text> >LINE BREAK HERE<
if (i != 2)
{
<text>, </text>
}
}
I like Darin's answer, and I would suggest removing your loop and replacing it with a more declarative statement, but if you don't want to go that far, try at least removing the line break:
#for (int i = 1; i < 3; i++)
{
<text>#i</text>if (i != 2){<text>, </text>}
}
Instead of writing out bits of text in different places each time round the loop, you could accumulate all the text in a StringBuilder, then outside the loop do #stringBuilderObject.ToString().
The problem is with the source that is generated. When you look at the actual source you get:
1
,
2
,
3
As you can see there is a lot of white space in there which browsers collapse down to a single space (look at the definition for normal).
Using a StringBuilder or string.Join is the way to fix this if all you're doing is outputting these three numbers. But if you're trying to do something else and this is a simplified example then see this blog post for a way of doing it using ol/ul and lis.
I might assume that it is not issue of Razor, but rather element is rendered with some margings.
Open FireBug (or Chrome or whatever) and see that it is really markup issue.
In you css file try to add
text { margin: 0 }

Resources