An html template is compiled into the application as a resource. A fragment of the HTML template looks like:
<A href="%PANELLINK%" target="_blank">
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
</A><BR>
%CAPTIONTEXT%
i like it like this because the larger resource HTML file contains styling, no-quirks mode, etc.
But as is always the case, they now want the option that the Anchor tag should be omitted if there is no link. Also if there is no caption, then the BR tag should be omitted.
Considered Technique Nº1
Given that i don't want to have to build entire HTML fragments in C# code, i considered something like:
%ANCHORSTARTTAGPREFIX%<A href="%PANELLINK%" target="_blank">%ANCHORSTARTTAGPOSTFIX%
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
%ANCHORENDTAGPREFIX%</A>%ANCHORENDTAGPOSTFIX%CAPTIONPREFIX%<BR>
%CAPTIONTEXT%%CAPTIONPOSTFIX%
with the idea that i could use the pre and postfixes to turn the HTML code into:
<!--<A href="%PANELLINK%" target="_blank">-->
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
<!--</A>--><!--<BR>
%CAPTIONTEXT%-->
But that is just rediculous, plus one answerer reminds us that it wastes bandwith, and can be buggy.
Considered Technique Nº2
Wholesale replacement of tags:
%AnchorStartTag%
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
%AnchorEndTag%%CaptionStuff%
and doing a find-replace to change
%AnchorStartTag%
with
"<A href=\"foo\" target=\"blank\""
Considered Technique Nº3
i considered giving an ID to the important HTML elements:
<A id="anchor" href="%PANELLINK%" target="_blank">
<IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%">
</A><BR id="captionBreak">
%CAPTIONTEXT%
and then using an HTML DOM parser to programatically delete nodes. But there is no easy access to a trustworthy HTML DOM parser. If the HTML was instead xhtml i would use various built-in/nativly available xml DOM parsers.
Considered Technique Nº4
What i actually have so far is:
private const String htmlEmptyTemplate =
#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN\"""+Environment.NewLine+
#" ""http://www.w3.org/TR/html4/strict.dtd"">"+Environment.NewLine+
#"<HTML>"+Environment.NewLine+
#"<HEAD>"+Environment.NewLine+
#" <TITLE>New Document</TITLE>"+Environment.NewLine+
#" <META http-equiv=""X-UA-Compatible"" content=""IE=edge"">"""+Environment.NewLine+
#" <META http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">"+Environment.NewLine+
#"</HEAD>"+Environment.NewLine+
#""+Environment.NewLine+
#"<BODY style=""margin: 0 auto"">"+Environment.NewLine+
#" <DIV style=""text-align:center;"">"+Environment.NewLine+
#" %ContentArea%"+Environment.NewLine+
#" </DIV>" + Environment.NewLine +
#"</BODY>" + Environment.NewLine +
#"</HTML>";
private const String htmlAnchorStartTag =
#"<A href=""%PANELLINK%"" target=""_blank"">";
//Image is forbidden from having end tag
private const String htmlImageTag =
#"<IMG border=""0"" src=""%PANELIMAGE%"" style=""%IMAGESTYLE%"">";
private const String htmlCaptionArea =
#"<BR>%CAPTIONTEXT%";
And i already want to gouge my eyeballs out. Building HTML in code is a nightmare. It's a nightmare to write, a nightmare to debug, and a nightmare to maintain - and it will makes things difficult on the next guy. i'm hoping for another solution - since i am the next guy.
My reputation points in this game already being low gives me the freedom to tell you quite plainly that you, sir or madame, are in serious need of XSLT. Failing this (and you probably will) you need to look at XML literals in VB.NET (which provides you with the template-based solution you are looking for...). Since I prefer to stay in C# (even though I was born and raised on VBA), I use XSLT.
Both of my unwelcome recommendations require the use of XHTML instead of HTML. This requirement alone is quite a turn off to many traditional developers. I can already see through your use of capital letters for HTML elements that you will find my remarks utterly useless. So I should stop writing now.
What about this: Store XML as your fragment:
<fragment type="link_img_caption">
<link href="%PANELLINK%" />
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" />
<caption text="%CAPTIONTEXT%" />
</fragment>
Pull it out, replace the placeholders with the "real" strings (that you have carefully XML-escaped of course),
...and use a simple XML transformation to produce HTML output:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="4.0" encoding="iso-8859-1" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="fragment" />
</xsl:template>
<xsl:template match="fragment[#type = 'link_img_caption']">
<xsl:choose>
<xsl:when test="link[#href != '']">
<a href="{link/#href}" target="_blank">
<img src="{img/#src}" style="{img/#style}" border="0" />
</a>
</xsl:when>
<xsl:otherwise>
<img src="{img/#src}" style="{img/#style}" border="0" />
</xsl:otherwise>
</xsl:choose>
<xsl:if test="caption[#text !='']">
<br />
<xsl:value-of select="caption/#text" />
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Other fragment types could be added because of the type attribute. There is much room to improve this, so look at it as an example of how it could be done.
Output:
<a href="%PANELLINK%" target="_blank">
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" border="0">
</a>
<br>
%CAPTIONTEXT%
and, if the link href is empty in the XML:
<img src="%PANELIMAGE%" style="%IMAGESTYLE%" border="0">
<br>
%CAPTIONTEXT%
Use a templating engine, like one of these.
1.) Don't use comments, you'll send useless data to the browser wasting bandwidth and encountering BUGs in IE.
2.) Would this not be better as some sort of method? (I'm not familiar with C#) but something like this makes more sense to me.
//using PHP in this example
function HTMLImage($imageData, $linkData){
var str = '';
//if there is link data, start <a> tag
$str .= '<a '.{expand any attributes}.'>';
//add image tag and attributes from $imageData
$str .= '<img '.{expand any attributes}.'/>';
//if there is link data, close <a> tag
$str .= '</a>';
return $str;
}
I would use Template Toolkit, unfortunately it is currently only implemented in Perl and Python.
test.pl:
use Template;
my $template = Template->new({
VARIABLES => {
ImageStyle => "default",
CaptionText => "Place Caption Here"
},
});
$template->process( 'test.tt', {
panel => {
link => "http://Stackoverflow.com/",
image => "/Content/Img/stackoverflow-logo-250.png",
alt => "logo link to homepage"
}
} );
test.tt:
[% IF panel.link -%]
<A href="[% panel.link %]" alt="[% panel.alt %]" target="_blank">
[%- END -%]
[%- IF panel.image -%]
<IMG border="0" src="[% panel.image %]" style="[% ImageStyle %]">
[%- END -%]
[%- IF panel.link %]</A>[% END %]<BR>
[% CaptionText %]
Outputs:
<A href="http://Stackoverflow.com/" alt="logo link to homepage" target="_blank">
<IMG border="0" src="/Content/Img/stackoverflow-logo-250.png" style="default">
</A><BR>
Place Caption Here
If the variable panel.link isn't defined it skips the anchor tags.
<IMG border="0" src="/Content/Img/stackoverflow-logo-250.png" style="default">
<BR>
Place Caption Here
Templates are a serious code smell. Take a look at how Seaside generates html.
[Edit] Another one where someone without a clue downvoted.
Related
I need to find an automated way to update href URLs in a HTML file with the corresponding image alt text the anchor tag is wrapping while also including leading and closing RPL text.
Start:
<img src="/images/image.jpg" alt="ALT_TEXT">
End:
<img src="/images/image.jpg" alt="ALT_TEXT">
Breaking down the new URL:
First Variable: ${clickthrough('<br>
Second Variable: ALT_TEXT<br>
Third Variable: ')}
Anyone know where I should start in designing a solution for this problem? What coding language might handle this?
The language that you are looking for is JavaScript.
Here is a working example that does what you mentioned. (and here is a codepen with the same example)
const anchorElements = document.querySelectorAll('a');
[...anchorElements].forEach((anchor) => {
const altText = anchor.querySelector('img').alt;
anchor.href = "${clickthrough('" + altText + "')}";
})
<img src="https://place-hold.it/300x100" alt="text1">
<img src="https://place-hold.it/300x100" alt="text2">
<img src="https://place-hold.it/300x100" alt="text3">
Hello i have list of products this my html
<telerik:RadListBox ID="RadListBox1" runat="server" DataSourceID="LinqDataSourceCategories" Height="200px" Width="250px" CssClass="ui-droppable" >
<EmptyMessageTemplate>
No records to display.
</EmptyMessageTemplate>
<ItemTemplate >
<div class="ui-draggable ui-state-default" data-shortid="<%#Eval("ID")%>">
<em>Active : </em><span><%# Eval("LoadProduct") %></span><br />
<em>ProductId: </em><span><%# Eval("ProductId") %></span><br />
</div>
</ItemTemplate>
</telerik:RadListBox>
I have Active that is say if LoadProduct true or false
in client it look like this
<em>Acrive : </em>
<span>False</span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
I want to replace text with img ,i need to check if <%# Eval("LoadProduct") %> ==true put img scr=/green.png/ else img scr=/red.png/ that clien will look like this
<em>Acrive : </em>
<span><img src='green.jpg'/></span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
Sow how it can be done?
To add if statement to HTML,
or to catch event that building all elements and there check if LoadProduct==true and append html to item?
try this
<em>Active : </em><span><%# Convert.ToBoolean(Eval("LoadProduct")) ? "<img src='green.jpg'/>" : "<img src='red.jpg'/>"%></span><br />
Come to think of it, I don't really like the idea of back-end conditionals in front-end.
Code-behind is one thing and frontside is the other - it's not a good idea to mix it if it isn't inevitable.
The purest way to get that would be to set the variable (or a function, in your case) in code-behind and just to show it in front-end, like:
Code behind:
protected string GreenOrRed(bool isLoadProduct)
{
return isLoadProduct ? "green" : "red";
}
(the function or variable has to be at least protected in order to be accessible in aspx page, because the aspx page is the derivative from base class of aspx.cs )
front-end:
<span><img src='<%# GreenOrRed((bool)Eval("LoadProduct")) %>.jpg'/></span>
After that, remeber to add
this.DataBind();
in your Page_Load() function.
Let the code-behind decide, let the front-end only show the result.
<%
if((bool)Eval("LoadProduct") == true)
{
Response.Write("src='green.jpg'");
}
else Response.Write("src='red.jpg'");
%>
Try this
<img src='<%# (bool)Eval("LoadProduct") ? "green.jpg" : "red.jpg" %>'/>
Is there any function or command that I can use to take the "pop-up" picture from this function:
<a class="thumbnail" href="#thumb">
<img src="productURL" width="100px" height="142px" border="0" />
<span>
<img src="productURL" />
<br />
<font face="arial">productname</font>
</span>
</a>
Be displayed in a table located to the right of the page?
Notes:
I'm using Dreamweaver CS6
Maybe there's a way to put, inside a class, that the pop up has to be shown inside a table, defined earlier?
EDITED
you can do that by this
in your html table cell tag add an id
HTML
<img src = "xyz.png" onmouseover="showimage();" onmouseout="hideimage();" />
and for table
<table><tr><td id="showimage"></td></tr></table>
Javascript
function showimage()
{
document.getElemtnById('showimage').append('<img src="xyz">');
}
function hideimage()
{
var elem = document.getElemtnById('showimage');
elem.removeChild(elem.childNodes[0]);
}
Regards.
Well this is probably kind of a silly question but I'm wondering if there's any way to have the generated markup in Jekyll to preserve the indentation of the Liquid-tag. World doesn't end if it isn't solvable. I'm just curious since I like my code to look tidy, even if compiled. :)
For example I have these two:
base.html:
<body>
<div id="page">
{{content}}
</div>
</body>
index.md:
---
layout: base
---
<div id="recent_articles">
{% for post in site.posts %}
<div class="article_puff">
<img src="/resources/images/fancyi.jpg" alt="" />
<h2>{{post.title}}</h2>
<p>{{post.description}}</p>
Read more
</div>
{% endfor %}
</div>
Problem is that the imported {{content}}-tag is rendered without the indendation used above.
So instead of
<body>
<div id="page">
<div id="recent_articles">
<div class="article_puff">
<img src="/resources/images/fancyimage.jpg" alt="" />
<h2>Gettin' down with responsive web design</h2>
<p>Everyone's talking about it. Your client wants it. You need to code it.</p>
Read more
</div>
</div>
</div>
</body>
I get
<body>
<div id="page">
<div id="recent_articles">
<div class="article_puff">
<img src="/resources/images/fancyimage.jpg" alt="" />
<h2>Gettin' down with responsive web design</h2>
<p>Everyone's talking about it. Your client wants it. You need to code it.</p>
Read more
</div>
</div>
</div>
</body>
Seems like only the first line is indented correctly. The rest starts at the beginning of the line... So, multiline liquid-templating import? :)
Using a Liquid Filter
I managed to make this work using a liquid filter. There are a few caveats:
Your input must be clean. I had some curly quotes and non-printable chars that looked like whitespace in a few files (copypasta from Word or some such) and was seeing "Invalid byte sequence in UTF-8" as a Jekyll error.
It could break some things. I was using <i class="icon-file"></i> icons from twitter bootstrap. It replaced the empty tag with <i class="icon-file"/> and bootstrap did not like that. Additionally, it screws up the octopress {% codeblock %}s in my content. I didn't really look into why.
While this will clean the output of a liquid variable such as {{ content }} it does not actually solve the problem in the original post, which is to indent the html in context of the surrounding html. This will provide well formatted html, but as a fragment that will not be indented relative to tags above the fragment. If you want to format everything in context, use the Rake task instead of the filter.
-
require 'rubygems'
require 'json'
require 'nokogiri'
require 'nokogiri-pretty'
module Jekyll
module PrettyPrintFilter
def pretty_print(input)
#seeing some ASCII-8 come in
input = input.encode("UTF-8")
#Parsing with nokogiri first cleans up some things the XSLT can't handle
content = Nokogiri::HTML::DocumentFragment.parse input
parsed_content = content.to_html
#Unfortunately nokogiri-pretty can't use DocumentFragments...
html = Nokogiri::HTML parsed_content
pretty = html.human
#...so now we need to remove the stuff it added to make valid HTML
output = PrettyPrintFilter.strip_extra_html(pretty)
output
end
def PrettyPrintFilter.strip_extra_html(html)
#type declaration
html = html.sub('<?xml version="1.0" encoding="ISO-8859-1"?>','')
#second <html> tag
first = true
html = html.gsub('<html>') do |match|
if first == true
first = false
next
else
''
end
end
#first </html> tag
html = html.sub('</html>','')
#second <head> tag
first = true
html = html.gsub('<head>') do |match|
if first == true
first = false
next
else
''
end
end
#first </head> tag
html = html.sub('</head>','')
#second <body> tag
first = true
html = html.gsub('<body>') do |match|
if first == true
first = false
next
else
''
end
end
#first </body> tag
html = html.sub('</body>','')
html
end
end
end
Liquid::Template.register_filter(Jekyll::PrettyPrintFilter)
Using a Rake task
I use a task in my rakefile to pretty print the output after the jekyll site has been generated.
require 'nokogiri'
require 'nokogiri-pretty'
desc "Pretty print HTML output from Jekyll"
task :pretty_print do
#change public to _site or wherever your output goes
html_files = File.join("**", "public", "**", "*.html")
Dir.glob html_files do |html_file|
puts "Cleaning #{html_file}"
file = File.open(html_file)
contents = file.read
begin
#we're gonna parse it as XML so we can apply an XSLT
html = Nokogiri::XML(contents)
#the human() method is from nokogiri-pretty. Just an XSL transform on the XML.
pretty_html = html.human
rescue Exception => msg
puts "Failed to pretty print #{html_file}: #{msg}"
end
#Yep, we're overwriting the file. Potentially destructive.
file = File.new(html_file,"w")
file.write(pretty_html)
file.close
end
end
We can accomplish this by writing a custom Liquid filter to tidy the html, and then doing {{content | tidy }} to include the html.
A quick search suggests that the ruby tidy gem may not be maintained but that nokogiri is the way to go. This will of course mean installing the nokogiri gem.
See advice on writing liquid filters, and Jekyll example filters.
An example might look something like this: in _plugins, add a script called tidy-html.rb containing:
require 'nokogiri'
module TextFilter
def tidy(input)
desired = Nokogiri::HTML::DocumentFragment.parse(input).to_html
end
end
Liquid::Template.register_filter(TextFilter)
(Untested)
Hey most of my issue has been solved but i have little problem
This is Html
<tr>
<td class="ttl">
</td>
<td class="nfo">- MP4/H.263/H.264/WMV player<br />
- MP3/WAV/еAAC+/WMA player<br />
- Photo editor<br />
- Organizer<br />
- Voice command/dial<br />
- Flash Lite 3.0<br />
- T9</td>
</tr>
Currently i am using this code provided by Stackoverflow User
var text1 = htmlDoc.DocumentNode.SelectNodes("//td[#class='nfo']")[1].InnerHtml;
textBox1.Text = text1;
know problem its is getting all text
with <br>
how i can remove <br> from it and put , between them
its should look like this
MP4/H.263/H.264/WMV player,- MP3/WAV/еAAC+/WMA player,- Photo editor,- Organizer,- Voice command/dial,- Flash Lite 3.0,- T9
Also how to get this
<div id="ttl" class="brand">
<h1>Nokia C5-03</h1>
<p><img src="http://img.gsmarena.com/vv/logos/lg_nokia.gif" alt="Nokia" /></p>
</div>
i am trying this
var text41 =
htmlDoc.DocumentNode.SelectNodes("//div
id[#class='brand']")[0].InnerText;
i get invalid token error
i only want C5-03 without nokia text
You can simply use a string.Replace("<br />", ""); to remove the <br /> tags.
Better yet, use the InnerText instead of InnerHtml, so no HTML comes through:
var text1 = htmlDoc.DocumentNode.SelectNodes("//td[#class='nfo']")[1].InnerText;
If you really want to replace all <br /> tags with a , you will indeed need to use Replace:
text1.Replace("<br />", ",");
To select the value in the <H1> tag, you could use:
var text42 = htmlDoc.DocumentNode.SelectNodes("//div[id='ttl']"/h1)[0].InnerText;