templating

개인적으로 템플릿 엔진 역사상 큰 전환점을 가져다 주었다고 꼽는 아이디어가 두 개 있다.

첫번째는 Kid1가 제안한 템플릿 상속블럭 개념. 그 전까지 웹 개발의 템플릿 작업은 어떻게 잘 템플릿을 쪼개서 인클루드할 것이가, 정도의 개념에서 벗어나지 못하고 있었는데, Kid가 제안한 템플릿 상속 아이디어는 템플릿 엔진 설계에 있어서 IoC에 해당하는 것이었다. 결국 Kid 자체는 XML 기반이라는 불편함과2 썩 빠르지 않은 구현 덕분에 망했지만, 템플릿 상속이라는 아이디어 자체는 워낙 훌륭해서 Django 템플릿에도 이어지게 되고, Django가 성공하면서 최근의 템플릿 엔진은 모두 상속 기능을 지니게 되었다.

두번째는 문자열 치환을 잘 하자는 기존의 모든 템플릿 엔진이 고수하던 근본적인 방식을 집어던지고 Haml이 제안한 트리(tree) 자체를 다루자는 획기적인 방식. 어쨌든 출력 결과가 XML/(X)HTML이고, 사람이 볼 데이터가 아니라 다른 소프트웨어가 볼 데이터라면 문자열을 직접 다룰 이유가 없다는 것이다! 대부분 사람들은 Haml이 Python과 같은 들여쓰기 문법을 채택했다는 점을 특징으로 보는데, 사실 들여쓰기 문법을 트리(tree)를 표현하기 좋은 방식으로서 선택된 부수적인 결정이지, 핵심적인 디자인 결정은 결국 문자열 대신 트리를 다루자는 관점이다.

템플릿 상속은 아이디어가 나온지 10년 가까이 된 현재 이미 널리 퍼진 상태고, 문자열 치환 대신 트리 자체를 다루자는 아이디어는 나온지 5년 정도 되었으니, 나머지 5년 안에는 널리 퍼졌으면 하는 바램이다.


  1. 사이트가 망했는지 접속이 안된다. PyPI 패키지 이름은 kid이다. 

  2. Kid 설계자가 딱히 XML 취향이라 그랬던 것은 아니고, 그 당시까지 Python 템플릿 엔진들은 죄다 XML 기반이었고 그게 대세였기 때문에 “무난하고 익숙한 방식”을 따르겠다는 디자인 의도였던 것 같다. 

Display Logic

Views are the most important entity, as they are what is directly requested by the client. For example, when the client request the context /main/hamburger, the object, settings and view associated with it are loaded.
 
The template is what is loaded around the view. This is determined by information provided by the /main/hamburger context.
 
The machine display mechanism diverges from most with the concept of components. Components can be though of as light-weight views, wherein they are written in PHP, but do not have an associated context object or JS controller. Components are subsets of each view, and to access a different components view, the name of the view has to be explicitly stated.

Components are never displayed on their own, they are always a part of a template or view. They are held in areas inside of templates and views. These areas act as containers for components to be loaded into.

To create called menu_space an area in a view: 

\_m\out::area(‘menu_space’);


As far as HTML goes, an area is really just a div that is of the _m_area CSS class who’s ID consists of _m_ appended to the front of the name provided. Areas nested inside of other areas are given ID’s accordingly. For example, an area named spaced inside of the area one would be given the ID _m_one_spaced.

To place the component called mike in the area one: 

\_m\out::comp('mike’,'one’);
_m.out.comp.('mike’,'one’);


To place the component called mike, which is located in the context /show/best in the area one: 

\_m\out::comp('mike@/show/best’,'one’);
_m.out.comp.('mike@/show/best’,'one’);


—To note, accessing components outside of your current context is not suggested at this point as JS Controller logic is connected to the context itself.—

To place the component called mike/great in the area spaced inside of the area one: 

\_m\out::comp('mike/great’,'one/spaced’);
_m.out.comp.('mike/great’,'one/spaced’);

Попробовал Twig в связке с Symfony2

Twig and Symfony2

Как-то так получилось, что из всех фреймворков на PHP больше всего понравился Symfony. До недавнего времени использовал нативную PHP-шаблонизацию, но в последних PR Symfony2 в качестве дефолтного и рекомендуемого шаблонизатора используется Twig (http://www.twig-project.org/).
Довольно давно присматривался к Twig'у, так как это один из немногих шаблонизаторов, который шаблоны сначала компилирует в нативный PHP, а потом попросту выполняет.

Решил доверится опыту гуру и в очередном проектике использовать Twig. B практически сразу наступил на грабли, о которых речь пойдет далее.

Keep reading

anonymous asked:

Do you have a certain wording as to how I can tell my teachers that I'm trans, via email or face to face? I'm really nervous, and not good with words.

emery says:

yes yes yes! there are a bunch of email templates floating around tumblr for coming out to teachers/parents, lemme grab some… well here’s my coming out letter, for some reason i CANNOT FIND any of the email things i KNOW i have seen… help, followers?

otherwise, here’s my suggestions:

Professor/Mr./Ms/ ____,

Hi, I’m a student in your ____ class and I wanted to let you know that I go by the name ___ and the pronouns ___. Please use these for me in class. Thank you!

Sincerely,
_____

it doesn’t need to be fancy or long, or even use the word “trans.” you can always explain later. good luck!

Gilt's JavaScript Templating Architecture

Templating is a powerful way of separating concerns on the front end. It’s a natural fit for Gilt’s platform, since much of our content comes to the front end from services that return JSON. Sometimes that JSON is rendered in JSPs with JSTL, but sometimes it’s better to render it with JavaScript.

Until recently, most JavaScript HTML rendering involved messy string concatenation, lots of looping, and an unholy marriage of logic and content in the same file. However, new templating engines, such as Handlebars, allow multiple logic-less templates to be created for the same content, with clean, easy-to-read syntax. Compare:

But which template engine to use? There are many currently vying for prominence. I didn’t want to hitch our wagon to any one engine, since many different pieces of Gilt code need to make templating calls and none of us knows the future, so I decided to create a middle-tier API that would accept any templating engine as a plugin. This is generally a good way to approach front end architecture, as it’s all too easy to scatter third-party dependencies throughout a large codebase, leading to difficult maintenance and requiring significant restructuring if the third-party code ever needs to be changed.

What It Is

There are three components in addition to the implementation code:

  • Gilt.Template, which exposes render(), register(), plugin.add() and plugin.get() methods
  • a template file saved using a directory and file naming convention
  • the chosen rendering engine code

How It Works

  1. Templates are stored in a Gilt.Template private cache, by a unique combination of name, engine, and version. Name is typically the type of feed or data that is being rendered, such as a wait list, a single product feed, or a cart. Version indicates which view of the data is required (“default” is the canonical view, and views can exist for third-party sites or other areas on the Gilt site such as a modal window or a specific page). Engine indicates which third-party rendering to use, with Handlebars as the default if none is specified.
  2. For flexibility, all rendering is asynchronous. The render() method does not actually write any markup; instead, it supplies the rendered markup to a passed callback function. This allows the template file or rendering engine to be lazy loaded at the time of invocation, rather than be already present on the page, and it recognizes that often the rendered template is needed for purposes other than writing immediately into an element on a page.
  3. Each template engine is an equal citizen, registered as a plugin with Gilt.Template. Handlebars and Dust are built-in, as we use both of them on the Gilt site; however, any additional template engine can be registered and used. Each plugin must provide a render() method, and optionally can provide a register() method (used, for example, in Dust compilation). When the implementation code calls Gilt.Template.render(), that method delegates to the plugin’s render() method.
  4. If the template is not available in Gilt.Template’s cache, it triggers an asynchronous load of the template file, looking by a naming convention of /templates/<type>/<version>.<engine>.js. For example, a template that handles the default view of a wait list feed using Handlebars would be stored at /templates/wait_list/default.handlebars.js. This convention allows for multiple views of the same data feed. Gilt.Template.render() takes an optional argument for an ajax service to use, with jQuery used by default. This allows for the possibility of use with a different base library, since this is the only point of third-party dependency.

How To Use

So, the three steps required to use the system are:

  1. Add a plugin using Gilt.Template.plugin.add() with the specific code required to interact with the chosen third-party templating engine. Handlebars support is built-in and, for reference, looks like this:

  2. Register a template with Gilt.Template.register(), indicating a unique combination of name, engine, and version. This could be done prior to calling render(); if not, render() will lazy load this template file, thereby calling register():

  3. Call Gilt.Template.render(), passing it the unique name, engine, and version to render, along with a callback to be provided with HTML. The render() method will load the plugin and call register() first if the template is unavailable. The following code is probably in the callback of an ajax request function:

tl;dr;

In summary, Gilt.Template:

  • allows for template storage by engine, version and name;
  • provides flexibility by providing rendered markup to a callback function;
  • treats all templating engines equally; and
  • speeds up page load by asynchronously loading template files.

Templates have helped us to separate our content data from its views on the site, and our middle-tier architecture has provided a consistent API and eliminated the need for third-party calls in the Gilt codebase.

Using Python's string.Template to Provide Templating for Third Parties

I had a great conversation this morning with Felix. At some point it was mentioned that you’d have to be a bit crazy (maybe good crazy) to decide to write your own templating system; there are already so many good options out there for almost every language. What was especially pertinent about the conversation, though, was that just yesterday the thought had crossed my mind that we might need to write our own simple templating system for Fiesta.

The problem

Our API tries to be as flexible as possible for developers. One aspect of that is allowing developers to use their own copy for some of the stock messages that Fiesta sends, like the “welcome” message that gets sent when a new member is added to a list. The problem is that some of those messages need to contain certain information that we want to be opaque to the API client (things like signed links, etc). The API client might get to decide where that information goes, but they don’t get to see the actual bits.

Sounds like a perfect job for a simple templating language: instead of sending us complete messages, the client sends Fiesta a template that gets filled in with the secret values. There doesn’t need to be any logic at all, just dead simple string substitution.

Our solution

My first thought was to just use Python’s replace method to replace predefined tokens with the right information. So we’d define tokens like {{ invite_url }}, and whenever those tokens appeared in the “template” we’d replace them with the proper value. This would be very simple, but could get a little messy as we add new tokens. Also, since it’s basically writing our own templating system, it’d only be a matter of time before we’d need to worry about handling escaping, invalid substitutions, etc.

I decided to use an existing templating system so we didn’t need to write anything new. We needed something that doesn’t allow logic in templates and is very simple to use (remember, our API users are the ones writing templates). I think the closest thing I found was Pystache, but even that seemed to have more functionality that we really needed (or wanted) to allow. That’s when I remembered that Python has basic string templates built-in. string.Template provides basic string substitution, with escaping. The default delimiter is $ (so tokens to get replaced look like $invite_url), but that is configurable as well. The best part is that it’s built-in, and no more difficult to use than the hacky replace call I contemplated above. Here’s the code that takes an incoming template from an API call and renders it with a generated “invite URL”:

template = string.Template(api_client_template)
text = template.safe_substitute(invite_url=invite_url)

And here’s what a client’s template might look like:

You've been invited to join a list! Click on the link below to accept the invitation:
$invite_url

I think string.Template is a great way to expose simple templates to third parties. Has anybody else dealt with a similar problem before? What did you come up with?

HTML templating and a little NLP

I’ve identified an issue whilst carrying out the templating of the collected feeds.

The issue stemming from html code within the feed’s content. Fortunately this problem only involves the templating area and I don’t really consider it as a major issue with the core of planet.js.

Regardless, I see presenting data as planet.js’ primary functionality so it’s important to present and produce a use case for others to see why planet.js is cool.

So why is HTML a problem?

Html isn’t a problem. In fact I wish to leave html in there. It gives semantic meaning and provides visual seperation between the feed articles. I’m using the Twitter Bootstrap stylesheet and that provides a good clean style for all of the feeds.

The problem stems from the feed object being displayed in the template. My philosophy is to provide a snippet of the feed and if a user wants to view more they can go ahead and click the title to the actual source.

When I provide the text_summary field instead of the full content to my template then it’s possible I leave a bunch of unclosed tags.

For example.

<p>Hello this is some feed content</p>

My text_summary field takes only a first chunk and can miss out the </p> tag.

So why not just close them?

I’ve considered it but examing the feeds closer I’ve understood that syndicators treat their RSS content very differently; a tumblr blog’s rss content is very different from Gizmodo (sourced from FeedBurner).

Gizmodo actually treat the text_summary portion of their content as only markup rules. That means that there is no human readable data in the text summary. Tumblr on the other hand is more relaxed.

But now that I think about it… I’m also able to rightfully reproduce a lot of markup too regardless of how the content is syndicated even on tumblr.

Since templating isn’t entirely important to planet.js I’ve decided to not use the text_summary and display full html data (text_full). This is an area I may most likely revisit in future however.

Database entries overlapping (core problem)

I’ve identified a potentially major issue with the object instancing aspect around the rss collection process. It involves feeds that are being collected around the same time are having their aggregation names mix up in the database. I’ve started a git issue on that so I don’t forget.

NLP

I’ve started development on a tagging system for planet.js. This is will remain in a seperate branch as a sort of plugin perhaps.

I was fortunate enough to find a node package which I believe will help me (https://github.com/fortnightlabs/pos-js).

This is an entirely different subject and I’ll cover it in my research blog.

Summary

Will continue to revise templating.

Aware of issue with database entries overlapping.

Making a tagging plugin for feed items using JavaScript Part of Speech tagger (expect research post to be up)

PHP MVC Framework

I’m currently writing an MVC framework for both personal and professional usage. It’s designed to be unobtrusive and give you a barebones approach to extending the root AppController with your own controllers.

Everything it does is at the most basic level allowing you to fundamentally several different websites using their own code on top, reducing the amount of updates to the core which may affect something else.

Once the AppController has been loaded via Bootstrap the rest is in your hands.

Templating will be an option which will, if turned on, be handled by a completely custom PHP template engine, with the ability to do more than just replace a couple of variables. Like Smarty, Empate as it is currently named allows you to execute loops, conditions, functions and more. It’s a work in progress but one which will see this framework gain usage from both myself building websites for freelance and in the workplace.

Like any good framework I too have added a dash of SPL awesomeness and have ensured that new classes will automatically be registered and unregistered as they’re called upon. It’s a bit like garbage collecting, you startup a new class, say… CountryController you don’t destroy it, by the end of the page, the AppController has kept track of everything, noticed you haven’t removed it from memory and will do it itself. It’s costly on memory, but I’m working to improve how it works, if we could pre-process the entire app before running this would be much more efficient.

I’ve collated a few frameworks and CMS’s to try and get a better picture of how they work, where I dislike them and how they might be improved.

I’m keeping my code minimal but need to allow the user to be able to rely on core code when they need it.