Razor CSHTML IF statement - razor

Anyone here that can help me? I have the following code:
#inherits umbraco.MacroEngines.DynamicNodeContext
#{
var node = #Model.NodeById(1257);
}
<div class="Top10">
<h1>Newest</h1>
#foreach (var article in node.Descendants().Where("Visible && (NodeTypeAlias = \"Article\" || NodeTypeAlias = \"sergrein\" || NodeTypeAlias = \"solomyndagrein\")").OrderBy("createDate desc").Take(10))
{
<h2>#article.createDate.ToString("dd/MM") | #article.title</h2>
}
</div>
What I want is: if #article.title is longer than e.g. 10 characters, it needs to return the 10 characters followed by ... (for example: "this_is_a_..."). If the #article.title is shorter than 10 characters, it can just show the full title length.
How can this truncating be done?

Try this
#(article.title.Length > 10 ? (article.title.Substring(0,10) + " ...") : article.title)

Normally I'd say do this in your Model, but it looks like you're using Umbraco's model.
So you could just do:
#inherits umbraco.MacroEngines.DynamicNodeContext
#{
var node = #Model.NodeById(1257);
}
<div class="Top10">
<h1>Newest</h1>
#foreach (var article in node.Descendants().Where("Visible && (NodeTypeAlias = \"Article\" || NodeTypeAlias = \"sergrein\" || NodeTypeAlias = \"solomyndagrein\")").OrderBy("createDate desc").Take(10))
{
{
var title = article.title;
if (title.Length > 10)
title = title.Substring(0,10) + "...";
}
<h2>#article.createDate.ToString("dd/MMM") | #title</h2>
}
</div>

this shall help,
#{
if(article.title.ToString().Length > 10)
{
article.title = article.title.Substring(0,10) + " ..."; //the format you desire
}
else
{
article.title; // default
}
}

Related

How to prevent my github page from making post title 'title-cased'

I have created a github page and have chosen one of proposed Jekyll themes called minima. To add a post I have created a file called 2018-11-16-My-first-post-on-github.md. However, the post title displayed is a text converted to title case: My First Post On Github, so every first letter in each word is made upper case. How can I prevent that? Is this theme-dependent?
exports.toTitleCase = function(str){
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return (str+'').replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match === 'tus') {
return match;
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
// Avoid uppercasing 'mod_deflate', apt-file - kvz
if (match.match(/.[\_\-\/\d]./)) {
return match;
}
// Avoid uppercasing '`frame`', '/sftp/import' - kvz
if (match.match(/(^[`\/]|[`]$)/)) {
return match;
}
// Avoid uppercasing: 'tmpfs' or anything that doesn't have a vowel - kvz
if (!match.match(/[aeiou]/)) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
exports.newPost = function (content, opts, cb){
var self = this;
var matches = [];
var oldTitle = '';
var newTitle = '';
var oldLine = '';
var heading = '';
var newLine = '';
var changes = [];
var words = [];
var frontMatter = content.split('---')[1];
if (frontMatter) {
matches = frontMatter.match(/^(title\s*:\s*)\"?(.+?)\"?[\ \t]*$/im);
oldTitle = matches[2];
newTitle = self.toTitleCase(oldTitle).trim();
oldLine = matches[0];
newLine = matches[1] + '"' + newTitle + '"';
if (oldLine !== newLine) {
changes.push({oldTitle: oldTitle, newTitle: newTitle});
content = content.replace(oldLine, newLine);
}
}
if (opts.body === true) {
matches = content.match(/^\#{1,6} ([a-zA-Z0-9\-\;\!\?\%\&\;\:\.\/\(\)\ ]+)$/mg)
for (var i in matches) {
words = matches[i].split(' ')
heading = words.shift();
oldTitle = words.join(' ');
newTitle = self.toTitleCase(oldTitle).trim();
oldLine = heading + ' ' + oldTitle;
newLine = heading + ' ' + newTitle;
if (oldLine !== newLine) {
changes.push({oldTitle: oldTitle, newTitle: newTitle});
content = content.replace(oldLine, newLine);
}
}
}
if (changes.length === 0) {
content = null;
}
return cb(null, content, changes);
};
Jekyll automatically converts your post title to uppercase upon import. You can fix this by using a plugin, or by using a YAML file or Front matter to specify your title value directly.

How can i skip image tab in string using AngularJS filter?

I want to skip img tab when i do filter.
I already tested but it is not ok.
It still filter img or src value.
So pls help me.
Here is my code
Filter
app.filter('highlight', function ($sce) {
return function (text, phrase) {
if (phrase) {
var matches = String(text).match(/<img.*?src="([^"]*)"[^>]*>(?:<\/img>)?/m);
var img_src = (matches && matches.length && matches[0]) ? matches[0] : '';
text = text.replace(img_src, "#");
text = text.replace(new RegExp('(' + phrase + ')', 'ig'),
'<span class="highlighted">$1</span>');
text = text.replace("#", img_src);
}
return $sce.trustAsHtml(text)
}
})
Controller
$scope.imgList = [];
imgList.push('<img src="image1.jpg">');
imgList.push('<img src="image2.jpg">');
imgList.push('Using <img src="image1.jpg">“this” instead of “scope” <img src="image3.jpg"/> <p>Post Description <img src="image4.jpg"/></p>');
HTML
<input ng-model="searchText" type="text">
<ul>
<li ng-repeat="img in imgList">
<p ng-bind-html="img | highlight:searchText"></p>
</li>
</ul>
I got the answer.
Filter be like this:
app.filter('highlight', function ($sce) {
return function (text, phrase) {
if (text && phrase) {
var matches = String(text).match(/<img.*?src="([^"]*)"[^>]*>(?:<\/img>)?/g);
if(matches && matches.length != 0){
for(var i = 0; i < matches.length; i++) {
text = text.replace(matches[i], "#_#" + i);
}
}
text = text.replace(new RegExp('(' + phrase + ')', 'ig'), '<span class="highlighted">$1</span>');
if(matches && matches.length != 0){
for(var i = 0; i < matches.length; i++) {
text = text.replace("#_#" + i, matches[i]);
}
}
}
return $sce.trustAsHtml(text)
}
})

Braces error occur by using 2 foreach in a single if condition

I got braces error when i try to add foreach to get all blocked users detail in else part of if condition.
Here is my code
#if (IsPost && Request["submit"] != null) //Search users engine
{
//search query here
<h2>Searched Users List</h2>
#foreach (var data in db.Query(searchUser))
{
pic = #data.ProfileImage;
userid = #data.UserID;
fname = #data.FName;
lname = #data.LName;
}
#if (userid == "") //user not exist
{
}
else
{
var id = ""; var blockuserid = "";
var CheckBlockedUser = "select * from Report where (Sender='" + #WebSecurity.CurrentUserName + "' AND SendedFor='"+Request["userid"]+"') AND IsBlock='1'";
foreach (var user in db.Query(CheckBlockedUser))
{
id = #user.Sender;
blockuserid = #user.SendedFor;
}
}
}
</div>
}
Any Idea Where i am doing wrong?
The foreach loop through which I get the information of all blocked user
foreach (var user in db.Query(CheckBlockedUser)) {
id = #user.Sender;
blockuserid = #user.SendedFor;
}

max lengt or else dots - How or what should i write?

I want the script to show max 26 letters and if there is more I want it to make (...) <-- so that you can se there is more letters in the link.
First I put a bit of a script I have for another site containing a variable to do that, however it doesn't work in RSS:
{
temp.Add(titel);
count++;
string titel_kort = titel;
if (titel.Length > 26)
{
titel_kort = titel.Substring(0, 26) + "...";
}
}
And this is the script I want to integrate to:
#using System.Xml.XPath;
#using System.Xml;
#{
try
{
XmlTextReader udBrudRSS = new XmlTextReader("http://tidende.dk/rss.aspx");
XmlDocument doc = new XmlDocument();
doc.Load(udBrudRSS);
XmlNodeList rssItems = doc.SelectNodes("//item");
var count = 0;
foreach (XmlNode node in rssItems )
{
count++;
if (count > 3) { break; }
<div class="nyhedlink">- #node["title"].InnerText</div>
}
}
catch {}
}
You could something like this :
using (var webclient = new WebClient())
{
var data = webclient.DownloadData("http://tidende.dk/rss.aspx");
var oReader = new XmlTextReader(new MemoryStream(data));
var xml = XDocument.Load(oReader);
var values = xml.XPathSelectElements("//item").Take(3).Select(p => new
{
Link = p.XPathSelectElement("//link").Value,
Title = (p.XPathSelectElement("./title").Value.Length > 26) ?
p.XPathSelectElement("./title").Value.Substring(0, 26).Trim() + "..." :
p.XPathSelectElement("./title").Value.Trim()
});
foreach (var item in values)
{
<div class="nyhedlink">- #item.Title</div>
}
}
Sometimes is better use WebClient to make the petition instead of XmlTextReader see this question for a good explanation.

LINQ2SQL - FirstItem

How do you get the first item only? It seems like I have to do the following otherwise i will get an error as if it was a multiple item and i can't get just the first element of it.
My goal is i would like to remove the foreach loop from the code below.
MetaDataPropertyBag propertyBag = new MetaDataPropertyBag();
var dbResultsOfType = db.spi_GetTypesByCaseType(caseType);
foreach (var item in dbResultsOfType)
{
if (item.ASSOC_TYPE_ID == primaryChildTypeID)
{
propertyBag.CaseTypeDesc = item.DESCRIPTION;
propertyBag.Required = item.IS_REQUIRED == 'Y' ? true : false;
propertyBag.Parent = item.PARENT_ID.Value;
propertyBag.Child = item.CHILD_ID.Value;
propertyBag.AssocTypeID = item.ASSOC_TYPE_ID;
propertyBag.CaseTypeID = item.CASE_TYPE_ID;
break; // Only one entry is requested
}
}
FirstorDefault should do it:
MSDN article on firstordefault
Here is one way to do it:
var first = dbResultsOfType.FirstOrDefault(item => item.ASSOC_TYPE_ID == primaryChildTypeID);
if (first != null) {
propertyBag.CaseTypeDesc = first.DESCRIPTION;
propertyBag.Required = first.IS_REQUIRED == 'Y' ? true : false;
propertyBag.Parent = first.PARENT_ID.Value;
propertyBag.Child = first.CHILD_ID.Value;
propertyBag.AssocTypeID = first.ASSOC_TYPE_ID;
propertyBag.CaseTypeID = first.CASE_TYPE_ID;
}