DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Software Design and Architecture Topics

article thumbnail
Effective Eclipse: Custom Templates
The same way I try to avoid the redundancy in my code, the same way I try to avoid the redundancy in my writing. I am lazy and templates do the most writing for me. Eclipse comes bundled with predefined templates, but they are too general and not all of them are too useful. The real power is in custom templates. In this article I would like to show you how to create them and list a few useful pieces for inspiration. What are templates Exactly as the name suggests, templates are little pieces of code with defined placeholders. An example of simple template is System.out.println(${text}); Each template has a name, which serves as a shortcut to the template itself. You type the name, press CTRL + SPACE and it will be expanded. Our first template would expand to [img_assist|nid=1424|title=|desc=|link=none|align=middle|width=186|height=19] I will not explain here what it all means, I already did this in my previous post on templates. What is important now, is that the ${text} placeholder (variable) was highlighted and can be edited immediately. The true power of templates can be fully seen in more complex templates. The first power point lies in the fact, that you can have more than one variable with same name. Our second template will have more variables: int ${increment} = ${value}; y = ${increment} + ${increment}; and will expand to [img_assist|nid=1428|title=|desc=|link=none|align=middle|width=204|height=45] When you start typing now, all occurrences of increment variable will be changed. You can then switch to the next variable by pressing TAB key. In the end, you can have [img_assist|nid=1425|title=|desc=|link=none|align=middle|width=110|height=43] in just three key presses - one for i, one for TAB and one for 2. To make it even better, the template system provides predefined variables, which will be expanded depending on their context. I will not list them, you can find them under the Insert variable button. [img_assist|nid=1426|title=|desc=|link=popup|align=middle|width=640|height=274] Notice, that you are not getting only a list, you are also getting a description and an usage example. To make it clear, I will illustrate one builtin variable - ${enclosing_type}. When this one is expanded you will get a name of the class (or interface, enum) in which your template was expanded. "But how can I use it?", I hear you asking. I have prepared few templates just for inspiration, I believe that after reading this you will find thousands others and I believe that you will create them and share them with us. Custom templates Open Window -> Preferences and type Templates into the search box. [img_assist|nid=1427|title=|desc=|link=popup|align=middle|width=640|height=578] You will get a list of all editors, and their respective template settings. This is because templates are closely bound to editors - you will get different builtin variables in different editors. Also note, that your list may vary from my list, it all depends on installed plugins. Now you must decide what type of template you would like to create. If it is a Java template, which will be applicable in context of classes, interfaces and enums, then choose Java -> Editor -> Templates. If you create a Java template you won't be able to use it in XML editor, that's quite expected. So click on the New button, to get a dialog. Here it is, in all its glory: [img_assist|nid=1430|title=|desc=|link=popup|align=middle|width=640|height=316] Name is the name of the template. Choose it well, because it will serve as a shortcut to your template. After you type the name of the template (or at least a few characters from its name) and hit CTRL+SPACE it will be expanded. Description is what you will see next to the template name when the template name is ambiguous. [img_assist|nid=1433|title=|desc=|link=none|align=middle|width=415|height=296] Pattern is the template body. And the Context? This varies in every editor. If you look in the combobox in Java templates, you will see Java and Javadoc. It is simple a context within the respective editor in which the template would be applicable. Check Automatically insert if you want the template to expand automatically on ctrl-space when there is no other matching template available. It is usually good idea to leave the checkbox checked, otherwise you would get a template proposal "popup". See what happens when I uncheck it on sysout template. [img_assist|nid=1432|title=|desc=|link=none|align=middle|width=256|height=46] If I would have checked it, it would automatically expand, as there is no other template matching sysout* pattern. My list So here is the list I promised. I have categorized it. Java (Java->Editor->Templates) logger - create new Logger private static final Logger logger = Logger.getLogger(${enclosing_type}.class.getName()); Notice the usage of ${enclosing_type} variable. This way you can create a logger in few hits. After the template expands, you will probably get red lines, indicating that Logger clas could not be found. Just hit CTRL + SHIFT + O to invoke the organize imports function. You are using shortcuts, aren't you? loglevel - log with specified level if(${logger:var(java.util.logging.Logger)}.isLoggable(Level.${LEVEL})) { ${logger:var(java.util.logging.Logger)}.${level}(${}); } ${cursor} Let me explain the details. ${logger:var(java.util.logging.Logger)} uses a builtin "var" variable. It starts with logger, the default name, in case the var variable finds no match. It is then followed by var(java.util.logging.Logger), what will evaluate to the name of the variable (member or local) of the specified type (in our case of the Logger type). Further, the ${cursor} variable marks the place where the cursor will jump after you press enter. So the result after expanding could be [img_assist|nid=1429|title=|desc=|link=none|align=middle|width=297|height=66] You might wonder what is the purpose of the if. It is there only for performance gain. If specified level is not allowed the logging method will never be called and we can spare JVM some string manipulation to build the message. readfile - read text from file Never can remember how to open that pesky file and read from it? Nor can I, so I have a template for it. BufferedReader in; try { in = new BufferedReader(new FileReader(${file_name})); String str; while ((str = in.readLine()) != null) { ${process} } } catch (IOException e) { ${handle} } finally { in.close(); } ${cursor} Maven (Web and XML -> XML Files -> Templates) dependency - maven dependency ${groupId} ${artifactId} ${version} ${cursor} parent - maven parent project definition ${artifactId} ${groupId} ${version} {$path}/pom.xml ${cursor} web.xml (Web and XML -> XML Files -> Templates) servlet - new servlet definition ${servlet_name} ${servlet_class} ${0} ${servlet_name} *.html ${cursor} JSP pages (Web and XML -> JSP Files -> Templates) spring-text - spring text field with label and error ${cursor} spring-checkbox ${cursor} spring-select ${cursor} spring-generic ${cursor} These are my favorites. They regularly save me a huge amount of time. Creating spring forms has never been easier for me. In some editor types you can set the template to 'new', for example, in XML editor it is new XML. This is really useful, as you can prepare the skeleton of a new file. For example, this is what I use to create new Spring servlet configuration for freemarker application. true messages Now, I can create new XML file from template and it will be ready to use. Before I knew about templates, I used to copy this from an older project, or search for it in Spring documentation. Now I don't have to.. [img_assist|nid=1431|title=|desc=|link=none|align=middle|width=640|height=201] If you can overcome the initial laziness and create your own templates from the pieces of code you really use, than this investment will shortly return in form of less typing. If you have some interesting templates, please, share them with us. You can download the templates mentioned in this post and import them using the Import button in the editor template settings.
February 28, 2008
by Tomas Kramar
· 232,688 Views · 1 Like
article thumbnail
Ruby: Escape, Unescape, Encode, Decode, HTML, XML, URI, URL
This example will show you how to escape and un-escape a value to be included in a URI and within HTML. require 'cgi' # escape name = "ruby?" value = "yes" url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T" # url: http://example.com/?ruby%3F=yes&var=T html = %(example) # html: example # unescape name_encoded = html.match(/http:([^"]+)/)[0] # name_encoded: http://example.com/?ruby%3F=yes&var=T href = CGI.unescapeHTML(name_encoded) # href: http://example.com/?ruby%3F=yes&var=T query = href.match(/\?(.*)$/)[1] # query: ruby%3F=yes&var=T pairs = query.split('&') # pairs: ["ruby%3F=yes", "var=T"] name, value = pairs[0].split('=').map{|v| CGI.unescape(v)} # name, value: ["ruby?", "yes"]
February 26, 2008
by Snippets Manager
· 4,020 Views
article thumbnail
Effective Eclipse: Don't write the code, generate it
I hope that we will never be able to generate applications. I would be without a job then and you probably too. But what we can generate are various repetitive and boring pieces of code. The first thing that can be generated is class file. You are using it, but you have probably never realized how much time does it save you. If there was no class skeleton generation, you would have to: create new file in the proper directory (with respect to package (and create the folders too)) and place the package statement at the beginning of a class. I will make a short stop here. I noticed that all people generate their classes, but not all of them specify implemented interfaces and extended class. Surely, you can generate the class and write the extends and implements part afterwards, but it involves moving the cursor, writing and eventually generating abstract or implemented methods. I found it much easier to press ALT + E (extend) to add extended class and ALT + A (add interface) to add interfaces in the new class wizard. My class will then come out with empty overridden methods and correct imports. If you look at the Source menu you can find more "Generate" commands. But none of them is so valuable and useful as Eclipse templates. They are the true gem in my daily work and it is pity they are hidden out of sight. And they are hidden well. What are they and how to get them? Templates serve as a shorthand for a snippet of code. You type in the magical word and it will be transformed into the snippet. Some examples: Type sysout and press CTRL + SPACE (the autocompletion) and it will be automagically changed to System.out.println(); with the caret waiting right in the middle between the parenthesizes. While we are here, let's explore the next interesting feature. Type "for" and press CTRL + SPACE to change it to a skeleton of a for loop. The for template is a showcase of templates' power. Notice the blue boxes around some of the commands. They represent the caret stop and you can move between them using the TAB key. Now, with the caret on "iterator", type the name of the variable representing the iterator. Its name will be changed in the whole loop as you type (the occurrences are marked with a light blue background). Now just two more TABs to change the collection variable and the type. Noticed the green line waiting in the empty line? It marks the position where the caret will jump when Enter key is pressed. So after changing the variable type you can just press Enter and the caret will jump to the empty line. When you use autocompletion the green marker is always somewhere around, waiting for you to press Enter. Every particular template is closely bound to editor. Each editor has its own defined set of templates, which are applicable only in that editor type. It is quite logical that the sysout template will not work in JSP editor. Furthermore, each template is applicable only within the specified context of the particular editor. There are two contexts in the Java editor for example, Java and Javadoc. To see list of all templates open Window -> Preferences and type templates into the search box. You will get a list of all editors and their respective template settings. Your list may vary from my list, because it depends on installed plugins. I encourage you to walk through the list to see what predefined templates are available. Not all of them are useful, but you need to see it, because what does not work for me might work for you. The true and real power of templates lies in custom templates, but I will leave this topic for the next week article. Apart from the fact, that it can expand templates, CTR + SPACE has few more interesting uses. It is an autocompletion shortcut and it can complete the names of variables or methods and in fact, it is its most obligate and the most famous usage. But it has some more surprises to offer. If you get used to it, you will be hitting it often, even in situations where there is obviously nothing to autocomplete. Or is it? Guess what is on the picture above? It is eclipse trying to autocomplete the name of a variable. It is pity it cannot read my mind. I often find myself hitting the shortcut in the middle of the string ever wondering why it doesn't complete the word. Never can remember the signature of a method you want to override? Never mind, hit CTRL + SPACE and you will get a list. It can assist you in private method creation, and it can guess what to complete even from the upper case letters. Warning: Using autocompletion and templates can lead to uncontrolled ctrl + space hitting, surprises and productivity boost.
February 22, 2008
by Tomas Kramar
· 102,834 Views
article thumbnail
Patching from Local History
Using patches is a popular way to share changes between the teammates or supply updates to software products to the customers. With IntelliJ IDEA, creating and applying versioned patches is quite simple and intuitive: you can do it from the main Version Control menu, or from the Changes tool window. However, IntelliJ IDEA suggests an additional way to create and apply your “personal” patches. As we have discussed earlier, numerous changes pass unnoticed by the version control systems, because you just do not check in every change you make to your files while working. You know that IntelliJ IDEA keeps your own “personal version control” – the local history. Besides the possibility to roll back to a certain revision, you can also create a patch on the base of a revision or action, share it with your colleagues, and apply it when necessary. Local history applies to the folders, files, members and fragments of text, but the technique of creating a patch is common in all cases. Let’s see how it’s done. Select a folder in the Project tool window, and choose Local History on its context menu. In the Local History view, right-click the desired revision, and choose Create Patch: [img_assist|nid=1204|title=|desc=|link=none|align=left|width=505|height=357] In the dialog box that opens, specify the name and location of the patch file: [img_assist|nid=1205|title=|desc=|link=none|align=left|width=415|height=136] An interesting possibility is suggested by the Reverse patch checkbox. If you check this option, IntelliJ IDEA will create a patch that rolls back the selected action. For example, it you have created a file, the patch will delete it. Applying your “personal” patch is done as usual, using the Apply Patch command on the main Version Control menu. If a patch file is stored in project, you can invoke this command on the context menu of the patch file in the Project tool window: [img_assist|nid=1206|title=|desc=|link=none|align=left|width=249|height=195]
February 21, 2008
by Irina Megorskaya
· 9,822 Views
article thumbnail
Binding a JTable to Swing Controls in NetBeans IDE
Here is an outline of a scenario that binds Swing controls to columns in a JTable, via the tools that NetBeans IDE provides.
February 20, 2008
by Geertjan Wielenga
· 183,899 Views
article thumbnail
Effective Eclipse: Shortcut Keys
The less you touch the mouse, the more code you can write. Below you will find a set of essential keyboard shortcuts that I love for Eclipse.
February 15, 2008
by Tomas Kramar
· 1,510,061 Views · 29 Likes
article thumbnail
Effective Eclipse: Setup Your Environment
Today, I was taught an important lesson. The lesson of effectiveness. I was attending a presentation, called "Python Django: Advanced web application in 40 minutes". The guy was a geek, he was writing the code in a very basic vim installation. I bet, that if he used something better (no offense, it was really basic installation and he was apparently no vim master) he could crack it in half the time. It was an "oh, I made a typo here" presentation. It was then, when I realized that you really need a good editor if you want to be productive. Choose your tool Just do it. Find what suits you best and use it. I found Eclipse. Basic setup The first thing you should do, is to set up your font. If you are using Windows, you are lucky, as the font looks probably good and is well readable. If you are using Ubuntu like me, you might have less luck. When I first started eclipse, I was stunned. The font was big and crappy. But not for too long. Open: Window->Preferences->General->Appearance->Color and Fonts->Basic->Text Font and change the font size to 8. Much better now. The font used is called Monospace, some people recommend Bitstream Vera Sans Mono. This is how it looked before and how it looks now. Before: After: I recommend lowering the font size for your whole desktop. You will be surprised how much more can you see now. You can improve the font rendering too. Don't be greedy Eclipse is running with very small memory by default, but there is really no reason to be greedy. Just give your toy what it needs. Fire up the text editor, open eclipse.ini and enter: -vmargs -Xms512M -Xmx1024M -XX:PermSize=128M -XX:MaxPermSize=256M The -Xms option specifies the minimum and -Xmx the maximum heap size. The same holds for PermSize and MaxPermSize. Heap is that part of memory, where all your objects live. PermGen means "Permanent Generation" and it is a part of memory where all permanent objects are stored. By permanent, I mean those, which are not going to be garbage collected (for example Strings, classes etc.). Here you can find a better explanation of what PermGen is. If you are running a linux box, you might experience OutOfMemoryError-s if you do not adjust memory size. The values provided above are only for example, you should enter the values appropriate to your RAM size. You can further tune the performance by providing additional arguments. In his article, Jim Bethancourt recommends using Throughput garbage collector (-XX:+UseParallelGC), Robi Sen recommends using CMS Collector (-XX:+UseConcMarkSweepGC) as more effective. Help, I am giving the crap all my memory and it still keeps OutOfMemoryErroring! The reason is that you are simply not giving it enough memory. But don't worry, you don't have to buy another memory module (well, unless you have 128MB RAM). It is possible that you have made a typo in eclipse.ini, or maybe you used wrong eclipse.ini or maybe it simply doesn't work. I cannot tell you how to fix it, but I can tell how much memory are you giving it. Open Window->Preferences->General and check the "Show heap status" checkbox. You should now see the memory status in the bottom right corner. If you see values which correspond to the values you entered, everything should be fine. Set it up You should really take a time to walk through all the options under Window -> Preferences and customize your eclipse installation. I am going to list few ba General Always run in background: when eclipse is doing something time consuming, it will bother you with a modal popup window showing the progress of a task. I used to dismiss the popup with "Run in background" button. I am usually not interested in watching the lazy progressbar. If you enable this option eclipse will no longer bother you, and all tasks will run in background by default. There is nothing worse than breaking your workflow with messages: Hey I am building, can you see? Appearance: You can set various font related options here. If you are interested, you can change the position of tabs from top to bottom. Editors->File associations: if you have some exotic extension you can map it to the appropriate editor here. If you have xml file called myfile.exotic you can map .exotic extension to the xml editor. Editors->Text Editors -> Show line numbers: If you like, you can see line numbers. Very useful. Editors->Text Editors -> Spelling: Eclipse comes bundled with a spell checking turned on by default. This is a good idea and I really liked it, until I opened localized messages for my web application. Every word in my file was marked as misspelled, I was looking at an yellow sea of warnings, editor became quickly unresponsive as it wasn't able to handle hundreds of spelling errors. I had to turn this feature off, at least until some kind of ignore list is implemented or some good folk creates dictionary for my language. Java Java->Code style: Under Cleanup and Formatter are code formatting settings which are applied everytime the file is saved. If you tune it, it can save you much time. Java->Code style->Code templates: Here you can find and edit various templates. The only thing I do here is changing the "new Type" template to show my real name as author instead of my operating system username. Run/Debug Run/Debug->Launching: In previous Eclipse releases if you hit the run button, the last launched application was started. In Eclipse 3.3 this behavior changed a bit, and the selected resource gets launched. I found it annoying as I usually have only one runnable class. You can switch to the old style by choosing the right option under Launch Operation fieldset. I know I am repeating myself, but it is essential that you walk through the options and set it, such that it works with you, not against you.
February 8, 2008
by Tomas Kramar
· 49,691 Views
article thumbnail
FreeMarker in NetBeans IDE 6.0: First Scenario
NetBeans IDE 6.0 provides support for FreeMarker, on many levels, covering a variety of scenarios. To not confuse things, I'll deal with each scenario in a separate article. The first scenario is aimed at NetBeans plugin authors. Authors of plugins frequently need to provide file templates to the users of their plugins. In short, FreeMarker is the language you can use to define these file templates. Your users will not deal with these file templates, at least not necessarily. Instead, they will use a wizard that will generate a file. Under the hood, the wizard will pass the values typed by the user (in the wizard's panels) to a FreeMarker file template for processing. In this article, I will show how you create such a file template and how to hook it into a wizard. In short, you will create a NetBeans module that provides a wizard that passes values to a FreeMarker template to generate a document when the user clicks "Finish" in the wizard. Take the steps below: Install the FreeMarker plugin. Install the FreeMarker Template Sample into NetBeans IDE 6.0. When you do this, you will be providing a sample project that will install syntax coloring and code completion for FreeMarker. (The sample plugin will also install other things, but so as not to confuse things, we won't look at these other features in this article.) Get the sample and install it. After you install the above plugin, go to Samples | NetBeans Modules in the New Project wizard (Ctrl-Shift-N). There you will find "FreeMarker Support Sample". Complete the wizard by clicking Next and Finish. Right-click the project node and install it. Now, all files that end in "ftl" or "template" will have FreeMarker syntax coloring and code completion. We will see this in action in a future step below. Create the plugin's initial source structure. Create a new module project, choosing NetBeans Modules | Module in the New Project wizard, and then completing the wizard, giving the project any name and code name base you like. In this case, I am interested in creating a module containing file templates for the "ItsNat" web framework. Therefore, I've called the module "ItsNatFileTemplates" and the code name base "org.netbeans.modules.itsnatfiletemplates". Generate a wizard. Let's generate the wizard's structure. Right-click the project node and choose New | Other. In the New Project wizard, choose Module Development | Wizard. Click Next. Choose "New File" and type "1" in "Number of Wizard Panels". Click Next. Type something in the class name prefix, such as "ItsNatServlet". Set something appropriate in the Category, Icon, and Package fields. Click Finish. Here's my source structure at this point: We don't need to know much about the generated code. We'll deal with the files one by one, as we need them. First, we will work with the iterator class, above it is called "ItsNatServletWizardIterator". We are going to modify it in such a way that we will add an existing panel, from the NetBeans sources, to our sequence of panels. Currently, we only have one and it is blank (look at "ItsNatServletVisualPanel1" in Design mode). So, we are going to replace this panel with an existing panel. The existing panel provides the fields "Class Name", "Project", and "Package", which we therefore will not need to create ourselves. Before continuing, open the layer file and add one attribute below the other attributes (or anywhere in the list) that modify the file template, to specify that we will be making use of the FreeMarker template engine: Set dependencies. In the next steps, we'll be adding code to the wizard iterator. Before doing so, we need to set some dependencies on modules that provide the NetBeans APIs that we will need. Therefore, set dependencies on the following: 'Java Project Support', 'Project API', and 'Project UI API' (right-click the project in the Projects window, choose Properties, click Libraries, then set dependencies on the above three and click OK). Specify our wizard panel. The first lines of the "getPanels()" method in the "ItsNatServletWizardIterator" are as follows: private WizardDescriptor.Panel[] getPanels() { if (panels == null) { panels = new WizardDescriptor.Panel[]{ new ItsNatServletWizardPanel1() }; Replace the above lines with these: private WizardDescriptor.Panel packageChooserPanel; private WizardDescriptor.Panel[] getPanels() { Project project = Templates.getProject(wizard); Sources sources = (Sources)project.getLookup().lookup(Sources.class); SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); packageChooserPanel = JavaTemplates.createPackageChooser(project,groups); if (panels == null) { panels = new WizardDescriptor.Panel[] { packageChooserPanel, }; The above is a bit of magic that replaces the wizard panel that we created with a panel that all Java source file wizards have in NetBeans IDE. Clean up. Fix imports (Ctrl-Shift-I), making sure to select "org.netbeans.spi.project.ui.templates.support.Templates" from the Fix All Imports box. You can now delete the two classes that form the panel. That is, just delete the wizard panel and the visual panel. You don't need them. Then, having a nice little module which includes just one Java class, just install it. Try the plugin. Now, remember the category you selected, back in step 4, when you created the wizard? If not, look in the layer.xml file, which should give you a clue. Now that you have installed your plugin, you should be able to find your new wizard in the New File wizard and invoke it from there. You should see something that looks like this: Create the FreeMarker file template. When you click Finish above, nothing happens. That's what this step is all about. Let's create our FreeMarker template. Right-click the package where your Java class is found, choose New | Other and then, in the New File wizard, choose Other | Empty File. (You'll see a FreeMarker category, installed by the plugin that we installed in step 1 above, but let's leave that for a future article.) Type "ItsNatServlet.ftl" (or something else, so long as the extension is ".ftl"). Then... specify your FreeMarker template, as shown in the screenshot below. And now you can see the syntax coloring and code completion provided by NetBeans IDE 6.0, via the plugin you installed at the start of this tutorial. (It is at this point that FreeMarker becomes relevant, so apologies for the time it took to get here, but this is the exact context where FreeMarker begins to be useful in this scenario.) Hook the FreeMarker file template into the plugin. Now that our FreeMarker template is done, let's hook it into our wizard so that, when Finish is clicked by the user, it is used to create the user's file. First, open the layer.xml file and add a "URL" attribute to the file name definition of the template, pointing to the location of our FreeMarker template, and changing the extension of the file name to specify that we wll create a file with the ".java" file extension: Back in the iterator, i.e., our Java class, look at the instantiate method: public Set instantiate() throws IOException { return Collections.EMPTY_SET; } First, set dependencies on "File System API", "Datasystems API", and "Nodes API". Then change the above method to the following: public Set instantiate() throws IOException { String className = Templates.getTargetName(wizard); FileObject pkg = Templates.getTargetFolder(wizard); DataFolder targetFolder = DataFolder.findFolder(pkg); TemplateWizard template = (TemplateWizard) wizard; DataObject doTemplate = template.getTemplate(); doTemplate.createFromTemplate(targetFolder, className); FileObject createdFile = doTemplate.getPrimaryFile(); return Collections.singleton(createdFile); } Now install the module again. This time, when you complete the wizard, you will have a new "ItsNat" servlet: If you don't have the "ItsNat" JAR files on the classpath, you'll also have... helpful red error marks in the editor. At this point, there are several open items to explore in the next part of this series—for example, we defined a set of variables in the FreeMarker template. They were magically replaced when we created the file via the wizard. How did that happen? Also, the FreeMarker template starts with lines of code that seem to relate to a project license. But... when the file was created, there was no project license. Why? These two questions and others will be handled in the next part of this series.
January 21, 2008
by Geertjan Wielenga
· 33,928 Views
article thumbnail
Multiple Backgrounds: Oh, What a Beautiful Thing.
The current spec for CSS3 includes support for multiple backgrounds in the background property. This is going to be fantastic for semantically-minded CSS developers. Many of the extra hooks that get thrown into HTML are there only to help out extra background images. Think about this common technique for blockquotes. This is some blockquoted text. The extra span in there is completely un-semantic, but it is often used so that you can get an extra background image in there. One for the quote mark in the upper left and one for the quote mark in the lower right: [img_assist|nid=349|title=|desc=|link=none|align=center|width=500|height=149] Blockquote example from here. With multiple backgrounds the extra hook is not needed. You can apply both the upper left and lower right image both to the blockquote element. Here is what the CSS will look like: blockquote { background: url('left.jpg') top left no-repeat, url('right.jpg') top right no-repeat, url('middle.jpg') top center repeat-x; } Notice you can set both the location and how it will repeat in each of the comma-separated backgrounds. I like the clean syntax of this, but it does present a problem. It is not backwards-compatible whatsoever. Older browsers that are not supporting this will just see no background at all, instead of for example, just the first image which would make sense. That means we can't just start using this in a forward-enhancement movement, unless we declare browser-specific stylesheets for the browsers that support it. At the time of this writing, only Safari is supporting multiple backgrounds. Here is a link to a quick example of some buttons utilizing multiple backgrounds in order to shrink and grow seamlessly. Remember, Safari-only right now. Remind you of anything? Sliding doors. Multiple backgrounds completely absolute sliding doors. Better semantics... No more complicated work-around techniques.... Oh, what a beautiful thing.
January 21, 2008
by Chris Coyier
· 10,987 Views
article thumbnail
Reverse TinyURL
PHP // Resolves a TinyURL.com encoded URL to its source. // Example: reverse_tinyurl('http://tinyurl.com/2ocfun') => "http://logankoester.com" function reverse_tinyurl($url) { $url = explode('.com/', $url); $url = 'http://preview.tinyurl.com/' . $url[1]; $preview = file_get_contents($url); preg_match('/redirecturl" href="(.*)">/', $preview, $matches); return $matches[1]; }
July 2, 2007
by Logan Koester
· 8,442 Views
  • Previous
  • ...
  • 754
  • 755
  • 756
  • 757
  • 758
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×