GRMustache formatted numbers, or an HTML Template Engine with Number Formatting in iOS - html

I'm not sure how to best go about this. I've tried solving this my own way, but failed so far. I tried using GRMustache, only to realize that I'm trying to display floats that just look hideous in the template I'm trying to use.
Basically, I have a model that I'm trying to have output as HTML via a template. Ideally, I just put the variable names/keypaths into the template and the template just gets parsed with the actual values (pretty much) rendered in place. But, the model I'm using uses floats for all its calculations and I'd really like them rendered as comma-separated integer strings (e.g. (float)9382.233325 => "9,382").
I can't seem to find any documentation in GRMustache that covers a situation like this, but I imagine this can't be an uncommon requirement. Does anyone know how to do this with GRMustache or through some other technique?

I'm the author of GRMustache.
There isn't, and there will never be any float formatting features in GRMustache, because there is already a perfectly well suited tool in the OS: NSNumberFormatter.
Since you're giving to GRMustache your model objects, here is my advice:
Declare a category on your model, and add a specific method for each of your formatted value:
#interface MYModel(GRMustache)
// name would match your original value property name
- (NSString *)formattedValue;
#end
In the implementation file, use a NSNumberFormatter:
#implementation MYModel(GRMustache)
- (NSString *)formattedValue
{
// Check the NSNumberFormatter reference for initializing
// the NSSNumberFormatter for your desired output.
NSNumberFormatter *formatter = [NSSNumberFormatter ...];
return [formatter stringFromNumber: [self value]];
}
#end
Beware creating many NSNumberFormatter instances may be costly. A good practice is to provide a shared method that returns a shared one. The code above is just a hint for the technique.
Finally, in your template, replace {{value}} tags with {{formattedValue}}.
Happy GRMustache!

GRMustache 1.12 now features a better API for number formatting: https://github.com/groue/GRMustache/blob/master/Guides/sample_code/number_formatting.md

Related

Is it possible to use the vaadin-grid inside a LitElement of a Polymer application?

What is the minimum example, if any, using the Polymer PWA (https://polymer.github.io/pwa-starter-kit/), to show correctly a vaadin-grid?
I tried many different combinations, but never a working one, with, often, this warning:
property-accessors.js:275 Polymer::Attributes: couldn't decode Array as JSON
Am I doing anything totally wrong?
Thanks
Andrea
Starting from the v5.2.0-beta1 we recommend using following Grid features:
column helper elements (vaadin-grid-filter-column, vaadin-grid-sort-column)
column convenience properties (path, header and text-align)
renderers for more complex cases where you previously used templates
See the example here: https://glitch.com/edit/#!/lying-blanket?path=app.js:29:42
https://lying-blanket.glitch.me/
Note: I'm using fetch API here for simplicity only, you can use XHR if necessary.

Github Jekyll how to make real page format same as preview

My github jekyll structure looks like next:
after I enter _posts and create .md file, it looks like:
the corresponding code is:
Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming.
The generics looks like:
```Java
List<String> list = new ArrayList<>();
//add item to list
String s = list.get(0);
```
or
```Java
public class Box<T> {
// T stands for "Type"
private T t;
//other code
}
```
The most commonly used type parameter names are:
```
E - Element (used extensively by the Java Collections Framework)
K - Key
```
We can see that the format is nice, such as it has syntax highlight.
I called it preview page
However, when I enter into my page by typing my github page url to see, it likes:
I called it real page
We can see that real page looks bad, e.g. there is no syntax highlight, there are multiple borders for quoting code syntax etc.
Thus, how to make the real page format is the same as preview page?
I suppose that you're relatively new to Jekyll so I have to do some clarification to you.
The result that you call "preview" is the result of your markdown parsed by GitHub. All markdowns have something in common so it's very likely that even if your parser is different almost all the things are parsed similarly. You could see a difference at the beginning of your "preview": the yaml content is displayed as a table.
Let's come back to Jekyll. If you're using the default settings, the parser of your code is kramdown (you could change it in the _config.yml file). When you execute Jekyll, it builds your website. That means that it parses your markdown and convert it to HTML. How it converts to HTML depends on a lot of things based on your configuration and plugin installed.
By default, you have no highlight. If you want to change it, take a look at the jekyll documentation. By default, it uses Rogue but you can also use Pigments or some other highlighter of your choice.
I don't think that this answer covers all your doubts and certainly not all your problems but it's to let you understand that your question, as it was posted, have not so much sense since your "preview page" and your "real page" are two completely distinct things. So google a bit, find what you want to achieve and ask a new question (you will surely have one in the near future).
Happy coding!

Internationalizing Very Long Texts With GWT (preferably including HTML)

I'm developing an application using GWT (first-timer) and am now at the stage where I want to establish a central structure to provide actual text-based content to my views.
Even though it's obviously possible to define those text-values inline (using UiBinder or calling the appropriate methods on the corresponding objects), I'd be much more comfortable storing them in a central place as is possible using GWT's Constants. Indeed, my application will only be available in one language (for now), so all-the-way i18n may seem overkill, but I'm assuming that those facilities might be best-suited for what I require, seeing how they, too, must have been designed with providing all (constant) text content in mind.
However, my application features several passages of text that are somewhat longer and more complex than your average label text, meaning they could span several lines and might require basic text formatting. I have come up with several ideas on how to fix those issues, but I'm far from satisfied.
First problem: Lengthy string values.
import com.google.gwt.i18n.client.Constants;
public interface AppConstants extends Constants {
#Constants.DefaultStringValue("User Administration")
String userAdministrationTitle();
// ...
}
The sample above contains a very simple string value, defined in the manner that static string internationalization dictates (as far as I know). To add support for another language, say, German, one would provide a .properties file containing the translation:
userAdministrationTitle = Benutzeradministration
Now, one could easily abuse this pattern to a point and never provide a DefaultStringValue, leaving an empty string instead. Then, one could create a .properties file for the default language and add text like one would with a translation. Even then, however, it is (to my knowledge) not possible to apply line-breaks for long values simply to keep the file somewhat well-formatted, like this:
aVeryLongText = This is a really long text that describes some features of the
application in enough detail to allow the user to act on a basis
of information rather than guesswork.
Second problem: Formatting parts of the text.
Since the values are plain strings, there isn't much room for formatting there. Instinctively, I would do the same thing as I would if I were writing the text straight into the regular HTML document and add HTML-tags like <strong> or <em>.
Further down the road, at the point where the strings are read and applied to the widget that's going to display them, there is a problem though: setting the value using a method like setText(String) causes that string to be escaped and the HTML-tags to be printed alongside the rest of the text rather than to be interpreted as formatting instructions. So no luck.
A way to solve this would be to disect the string provided by the i18n file and isolate any HTML-tags, then baking the mess together again using a SafeHtmlBuilder and using that to set the value of the widget, which would indeed result in a formatted text being displayed. That sounds like much of an overcomplication though, so I don't quite like that idea.
So what am I looking for now, dear user who actually read this all the way through (thanks!)? I'm looking for solutions that don't require hacks like the ones described above and provide the functionality that I'm looking for. Alternatively, I welcome any guidance if I'm on the wrong path entirely (GWT first-timer, as I mentioned one eternity ago :-) ). Or basically anything that's on topic and might help find a solution. An acceptable solution, for example, would be a system like the string value files used in Android development (which allows for HTML-styling the texts but obviously requires the containing UI elements to accept that).
Fortunately, there is a standard solution that you can use. First, you need to create a ClientBundle:
public interface HelpResources extends ClientBundle {
public static final HelpResources INSTANCE = GWT.create(HelpResources.class);
#Source("account.html")
public ExternalTextResource account();
#Source("organization.html")
public ExternalTextResource organization();
}
You need to put this bundle into its own package. Then you add HTML files to the same package - one for each language:
account.html
account_es.html
organization.html
organization_es.html
Now, when you need to use it, you do:
private HelpResources help = GWT.create(HelpResources.class);
...
try {
help.account().getText(new ResourceCallback<TextResource>() {
#Override
public void onError(ResourceException e) {
// show error message
}
#Override
public void onSuccess(TextResource r) {
String text = r.getText();
// Pass this text to HTML widget
}
} catch (ResourceException e) {
e.printStackTrace();
}
You need to use HTML widget to display this text if it contains HTML tags.
If you're using UiBinder, i18n support is built-in. Otherwise, use Messages and Constants and use the value with setHTML rather than setText.
For long lines, you should be able to use multiline values in properties files by ending lines with a backslash.

How do I determine the current pages document type in umbraco?

I have what I feel is a very simple question about Umbraco, but one that has as of yet no apparent answer.
I have a razor template, standard stuff, with # displaying variables and some inline C# code.
At one point in the template I use:
#Umbraco.RenderMacro("myCustomMacro");
no problems there, everything works as expected.
Now, this macro is inserted on every page (it's in the master template) but I have a page property that allows the content authors to turn it on and off via a check box in the page properties, again so far so good everything works perfectly.
However I now find that for a certain "document type" this component MUST be displayed, so I've been trying to find a way to perform that check.
Now in my mind, this should be as simple as doing something like this:
#{
if(CurrentPage.documentType == "someDocTypeAliasHere")
{
//Render the macro
}
else
{
// Render the macro only if the tick box is checked
}
}
as I say, this is (or I believe it should be anyway) a very simple operation, but one that so far does not seem to have a result.
What Have I tried so far?
Well apart from reading every page on our-umbraco that mentions anything to do with razor & the #CurrentPage variable, Iv'e been through the razor properties cheat sheet, and tried what would appear to be the most common properties including (In no specific order):
#CurrentPage.NodeTypeAlias
#CurrentPage.NodeType
#CurrentPage.ContentType
#CurrentPage.DocumentType
and various letter case combinations of those, plus some others that looked like they might fit the bill.
Consistently the properties either don't exist or are empty so have no useable information in them to help determine the result.
So now after a couple of days of going round in circles, and not getting anywhere I find myself here..
(Please note: this is not a search the XSLT question, or iterate a child collection or anything like that, so any requests to post XSLT, Macros, Page templates or anything like that will be refused, all I need to do is find a way to determine the Document Type of the current page being rendered.)
Cheers
Shawty
PS: Forgot to mention, I'm using
umbraco v 4.11.8 (Assembly version: 1.0.4869.17899)
Just in case anyone asks.
In Umbraco 7 use currentPageNode.DocumentTypeAlias
In Umbraco 7.1 I use: #if (#CurrentPage.DocumentTypeAlias == "NewsItem")
think you do actually need to create a node each time when you are on the page to access the pages properties like nodetypealias and stuff, try this i have the same kind of functionality on my site, http://rdmonline.co.uk/ but in the side menu where depending on the page/section it shows a diff menu links.
#{
var currentPageID = Model.Id;
var currentPageNode = Library.NodeById(currentPageID);
if (currentPageNode.NodeTypeAlias == "someDocTypeAliasHere")
{
//Render the macro
}
else
{
// Render the macro only if the tick box is checked
}
}
Let me know if this works for you.
This is a bit unrelated to this post, but searching Google brought me to this post, so I thought I'd share in case anoyne else is dealing with this issue: In Umbraco 7, to get all content in the site for a specific type:
var articles = CurrentPage.AncestorOrSelf(1).Descendants()
.Where("DocumentTypeAlias == \"BlogPost\"").OrderBy("CreateDate desc");
If your razor view inherits from Umbraco.Web.Mvc.UmbracoViewPage, you could also use UmbracoHelper:
#if (UmbracoHelper.AssignedContentItem.DocumentTypeAlias.Equals("NewsItem")) { ... }
Querying for a specific DocumentType is also easy:
UmbracoHelper.AssignedContentItem.Descendants("NewsItem")
This code will recursively return the list of IPublishedContent nodes.
If you wish to use this list with your specific DocumentType information, these items would have to be mapped to the specific type. Other than that, IPublishedContent gives you the basic information for the nodes.
I've later saw that you have been using an older version of Umbraco. :)
This implementation is only for v7.

Grep and Extract Data in Perl

I have HTML content stored in a variable. How do I extract data that is found between a set of common tags in the page? For example, I am interested in the data (represented by DATA kept between a set of tags which one line after the other:
...
<td class="jumlah">*DATA_1*</td>
<td class="ud">*DATA_2*</td>
...
And then I would like to store a mapping DATA_2 => DATA_1 in a hash
Since it is HTML I think this could work for you?
https://metacpan.org/pod/XML::XPath
XPath is the way.
Since it's HTML, you probably want the XPath module made for working with HTML, HTML::TreeBuilder::XPath.
First you'll need to parse your string using the HTML::TreeBuilder methods. Assuming your webpage's content is in a variable named $content, do it like this:
my $tree = HTML::TreeBuilder->new;
$tree->parse_file($file_name);
Now you can use XPath expressions to get iterators over the nodes you care about. This first expression gets all td nodes that are in a tr in a table in the body in the html element:
my $tdNodes = $tree->findnodes('/html/body/table/tr/td');
Finally you can just iterate over all the nodes in a loop to find what you want:
foreach my $node ($tdNodes->get_nodelist) {
my $data = $node->findvalue('.'); // the content of the node
print "$data\n";
}
See the HTML::TreeBuilder documentation for more on its methods and the NodeSet documentation for how to use the NodeSet result object. w3schools has a passable XPath tutorial here.
With all this, you should be able to do pretty robust HTML parsing to grab out any element you want. You can even specify classes, ids, and more in your XPath queries to be really specific about which nodes you want. In my opinion, parsing HTML using this modified XPath library is a lot faster and more maintainable than dealing with a bunch of one-off regexes.
Use HTML parsing modules as described in answers to this Q - HTML::TreeBuilder or HTML::Parser.
Purely theoretically you could try doing this using Regular Expressions to do this but as noted in the linked question's answers and countless other times on SO, parsing HTML with RegEx is a Bad Idea with capital letters - too easy to get wrong, too hard to get well, and impossible to get 100% right since HTML is not a regular language.
You might try this module: HTML::TreeBuilder::XPath. The doc says:
This module adds typical XPath methods to HTML::TreeBuilder, to make it easy to query a document.