Tài liệu Instant Galleria How-to Recipes to make you an expert user of the Galleria JavaScript framework ppt

70 573 0
Tài liệu Instant Galleria How-to Recipes to make you an expert user of the Galleria JavaScript framework ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info Instant Galleria How-to Recipes to make you an expert user of the Galleria JavaScript framework Nathan Van Gheem BIRMINGHAM - MUMBAI www.it-ebooks.info Instant Galleria How-to Copyright © 2013 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: February 2013 Production Reference: 1080213 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-84969-660-9 www.packtpub.com www.it-ebooks.info Credits Author Project Coordinator Nathan Van Gheem Reviewer Esha Thakker Proofreader Victor Berchet Lawrence A Herman Acquisition Editor Production Coordinator Usha Iyer Conidon Miranda Commissioning Editor Ameya Sawant Technical Editor Kirti Pujari Cover Work Conidon Miranda Cover Image Conidon Miranda www.it-ebooks.info About the Author Nathan Van Gheem primarily works on Python web solutions He also has extensive experience with JavaScript and integrating JavaScript solutions in web applications He is involved with the Plone Python CMS open source community where he is the UI team leader and is on the Security team I would like to thank my family for the sacrifice of time they put up with, Wildcard Corp for giving me an opportunity to work on interesting projects, and Kim Nguyen for encouraging and enabling me to challenge myself with open source software www.it-ebooks.info About the Reviewer Victor Berchet was introduced to web development in 2007 by playing with Google Maps, JavaScript API, and PHP, after having spent 10 years in the domain of embedded software development He became a freelance Web Engineer in 2010 by founding Suumit, his own company Most of the projects Victor works on involve either JavaScript mapping or the Symfony2 PHP framework He is pretty much engaged in open source software and is one of the top contributors of Symfony2 www.it-ebooks.info www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library Here, you can access, read and search across Packt’s entire library of books.  Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print and bookmark content ff On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books Simply use your login credentials for immediate access www.it-ebooks.info Table of Contents Preface 1 Galleria How-to Setting up the development environment (Simple) Your first gallery (Simple) Configuring Galleria (Simple) Installing themes (Simple) Creating your own theme (Medium) Creating mobile friendly themes (Simple) Installing plugins (Simple) Using the Flickr plugin (Medium) Creating a plugin (Advanced) Using the API (Medium) Alternative image data structures (Simple) Optimizing Galleria (Simple) Adding images dynamically (Medium) Triggering Galleria (Advanced) Recording image views with Google Analytics (Medium) Handling errors gracefully (Medium) Creating tests for customizations (Advanced) Web application integration (Advanced) www.it-ebooks.info 12 14 15 20 23 24 27 30 35 40 41 44 46 48 50 54 www.it-ebooks.info Preface Galleria is a JavaScript framework for building beautiful image galleries for the web It comes packed with responsive web design support and swipe for mobile devices With its flexible theming system, you'll be able to customize it to your needs or you can use one of the many available themes It is open sourced under the MIT license and comes packed with a free classic theme Galleria has a large user base with many web application add-ons already provided on various platforms It's an obvious choice for creating beautifully customized galleries on your website If you want to integrate Galleria to create your own beautiful image galleries for the web, Galleria How-to is the book you need Using concise recipes, Galleria How-to will take you from creating and configuring your first gallery to creating themes and plugins, using the Galleria API and integrating with web applications What this book covers Setting up the development environment (Simple) details how to set up a development environment to start developing with Galleria Your first gallery (Simple) introduces creating a simple gallery Configuring Galleria (Simple) details how to configure Galleria with JavaScript and HTML attributes Installing themes (Simple) discusses how to install and use different themes Creating your own theme (Medium) details the process of creating custom themes with JavaScript and CSS Creating mobile friendly themes (Simple) introduces how to create mobile friendly themes using responsive web design www.it-ebooks.info Galleria How-to /* Standard analytic JavaScript source Please replace "" with your GA code */ var _gaq = _gaq || []; _gaq.push(['_setAccount', '']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); How to it The Google Analytics JavaScript includes an API to push page tracking manually to Google In our case, we'll hook into a Galleria image view event and send out a Google Analytics page tracker request The Google Analytics JavaScript API uses AJAX to send out the tracker request so a new page load isn't required $(document).ready(function(){ Galleria.loadTheme( ' /themes/classic/galleria.classic.min.js'); Galleria.run('#galleria'); Galleria.ready(function(options) { var galleria = this; galleria.bind('loadstart', function(e) { var url = e.imageTarget.src; var host = window.location.hostname; _gaq.push(['_setCustomVar', 1, "galleryView", "yes", 1]); _gaq.push(['_trackPageview', url.substring(url.indexOf(host) + host.length)]); }); }); }); 47 www.it-ebooks.info Galleria How-to The code pattern here follows much of what has been done throughout the book We're registering an event handler that'll fire when a new image is shown in the gallery Then, we're sending the tracker request to the Google Analytics API We make sure to only get the full path of the image to track in Google Analytics The host name is not allowed How it works The Google Analytics API provides an API to push page tracking to it manually in JavaScript We're just utilizing that API in this example with basic Galleria API programming There's more Google Analytics has a robust JavaScript API if there is a need to something more fancy Check out their documentation available at https://developers.google.com/ analytics/devguides/collection/gajs/methods/ Handling errors gracefully (Medium) If certain images cannot be loaded, handle it in a graceful way so users aren't confronted with a broken, ugly gallery Getting ready There are two types of Galleria errors, fatal, and warnings Fatal errors will throw a JavaScript exception and stop all following JavaScript from running Warnings will cause Galleria to not show an image and then present an error box to the user Fatal errors can result from the following reasons: ff Not being able to load the theme file ff Not finding that target HTML element to create the gallery ff Hitting the browser stylesheet limit (Internet Explorer related) ff Not finding the theme ff Not determining gallery width and height ff Width or height is too small for displaying gallery 48 www.it-ebooks.info Galleria How-to Warnings can result from the following: ff Another gallery instance already running ff HTML running in quirks mode ff Failing to load image data ff Not extracting width and height from image ff Not finding an image ff Not being able to scale an image We'll use two separate methods to handle each of these types of errors in Galleria to help handle them better To implement our error handlers, let's create a file named errors-example.html in the development directory The contents can be a very basic Galleria setup as follows: $(document).ready(function(){ Galleria.loadTheme( ' /themes/classic/galleria.classic.min.js'); Galleria.run('#galleria'); }); 49 www.it-ebooks.info Galleria How-to How to it Since fatal errors prevent other JavaScript from executing on the page, it's especially important that we handle these errors In addition, it's important to give the user an indication that the Galleria failed to load As for warnings, they'll most likely be caused by incorrect configuration but there are still ways to prevent them from being too much of a nuisance To override the default error handling strategy, let's work through the following code: $(document).ready(function(){ Galleria.loadTheme( ' /themes/classic/galleria.classic.min.js'); Galleria.run('#galleria', { debug: false, dummy: 'images/dummy.jpg' }); }); How it works Setting debug to false prevents Galleria from throwing a JavaScript fatal error and stopping the execution of any additional JavaScript In addition, setting a dummy image tells Galleria to use that image instead of showing an error message or failing when an image fails to load Creating tests for customizations (Advanced) This recipe creates tests for Galleria customizations that can be run across many browsers This will allow you to ensure the quality of your customizations via automated testing Getting ready In the tests we're going to write, we'll be using the Selenium test framework with the Firefox web browser The advantage of Selenium is that it comes with an IDE plugin so novices can even write tests The difficultly level is ideal to cover in this book We'll be using Selenium to record user interactions with our Galleria customizations Once these interactions are recorded, they can then be tested against any additional functionality or changes to ensure that everything is still working as expected 50 www.it-ebooks.info Galleria How-to Before we get started, please download the Firefox web browser if you have not already done so, available at http://www.mozilla.org/firefox Follow the instructions to download and install Then, open Firefox and visit http://seleniumhq.org/download/ and follow the instructions to download and install the Firefox Selenium IDE plugin Make sure to restart Firefox after the plugin is installed Finally, open up Selenium IDE by clicking on Tools in the menu bar and then selecting the Selenium IDE item in the menu There should be a Selenium IDE window like the one in the following screenshot: Once Selenium is set up, locate the myfirstgallery.html file that we created in the Setting up the development environment recipe We'll be creating tests for that gallery 51 www.it-ebooks.info Galleria How-to How to it First, open the myfirstgallery.html file in Firefox Then, click on the record button (red button in the upper right-hand corner) and then start using the gallery as the user would Selenium will be recording all the actions that we perform Once all the functionality is tested, click on the record button once more to stop recording Now, before we run the test just created, reduce the speed all the way down It should look like the following screenshot: Modifying this prevents Selenium from running the test action too quickly If it ran too quickly, Galleria wouldn't finish the transitions before the next action is performed Finally, click the play button to run the test we just recorded The whole test suite should run without failure if it was done correctly Inspect the source tab of the recorded test It should contain something similar to the following code snippet: New Test New Test 52 www.it-ebooks.info Galleria How-to open file:///path/to/galleria/development/myfirstgallery.html click css=div.galleria-image-nav-right click css=div.galleria-image-nav-right click css=div.galleria-image-nav-right The test code is actually just simple HTML table markup with events and element selectors, so from here it's possible to save these tests as files to version control and run them on different machines and browsers In addition to the actions that were recorded, it would be beneficial to also include assert statements to make sure certain elements are present in the DOM as each action is performed Inspect Selenium IDE for details on using more commands and tests How it works Selenium IDE allows us to record all the actions being performed in the browser Then the Selenium test driver plays the tests defined against a web browser, in our case Firefox Those tests can be run against a Selenium server that is set up to test against multiple browsers and operating systems Read more about the selenium testing framework Selenium has a vast API and documentation area on its website Anyone who is interested in learning more about it should read it, available at http://seleniumhq.org/ 53 www.it-ebooks.info Galleria How-to Web application integration (Advanced) Integrate Galleria with a web application platform or CMS In this recipe, we'll cover creating a web application that reads images from a filesystem directory Getting ready For the sake of this example, we'll be introducing a new programming language and platform to work with The purpose is to show how a possible web application integration would work We'll be using the Python programming language and the Flask web application framework Both are known for their ease of use so hopefully it'll be easy to understand for someone that has no experience with the technologies It's fine to skip the following paragraphs if there is no interest in learning the Python tools used here Before we start, install Python We'll be using Python 2.7 in this example Please visit http://www.python.org/getit/ for information on installing Command line examples will be given for both Unix Bash and Windows Once Python is installed, enter the following command in the cmd.exe application (Windows): C:\Python27\Scripts\easy_install.exe Flask Enter the following command for Unix: sudo easy_install Flask Next, create files named app.py and app.html in the development directory we've been working in We'll use those files for the web application we'll write How to it In our sample Flask web application, we're going to dynamically read images from the filesystem to create our gallery with and use a templating engine to generate the HTML markup required for the gallery Here, we're using a templating engine to dynamically render HTML markup Previously, the HTML markup we used was manually crafted Since the following code snippet is a bit longer, please read the inline comments The contents of app.py will look like the following: import os from flask import Flask, render_template # Create the application app = Flask('Galleria', static_folder=" /", 54 www.it-ebooks.info Galleria How-to static_url_path="/static", template_folder="./") # Set the directory where images are stored image_dir = os.path.join(os.path.dirname( file ), 'images') @app.route("/") def index(): """ Run this function for the index page of the web application Images on the filesystem are expected to be in the format for thumbnails: image#-200px.jpg And this format for large size: image#-1600px.jpg """ images = {} for filename in os.listdir(image_dir): # if the filename does not start with image, # it's not a valid gallery image if not filename.startswith('image'): continue # let's find the scale size name, size = filename.split('-') if name not in images: images[name] = {} if size.startswith('200px'): # thumbnail images[name]['thumb'] = filename else: # full size images[name]['image'] = filename # render the app.html template with the image data we gathered return render_template('app.html', images=images.values()) if name == " main ": app.run() Here we're setting up the Flask app and setting up one URL—the index page of the site What the index page of the site shows depends on what is returned in the function we have defined In our case, we're rendering a template with the values of the images we found on the filesystem 55 www.it-ebooks.info Galleria How-to The app.html file will then look like the following code: $(document).ready(function(){ Galleria.loadTheme( '/static/themes/classic/galleria.classic.min.js'); Galleria.run('#galleria'); }); {% for image in images %} {% endfor %} The important part of this HTML code is bolded We're iterating over the set of images provided to the template and rendering the new image URL as the web application knows it Finally, to run the application, in the command line, move to the directory where the app.py file is located: cd galleria/development Then, run the following command to start up the web application (Windows): C:\Python27\python.exe app.py Run the following command to start up the web application (Unix): python app.py 56 www.it-ebooks.info Galleria How-to We should get the following output, letting us know that the Flask app is running correctly: Finally, in a web browser, enter the address: http://127.0.0.1:5000/ If all went well, we should see a gallery with the classic theme on the page How it works This example works much like the rest of the Galleria example with the exception of the image HTML markup being generated by Python code and the JavaScript, CSS, and images resources being served by the web application The advantage of using a web application is that the images used can be dynamically generated With our application, we could simply add photos to the images directory, also naming them according to the standard we're using, and the gallery will automatically begin using those images Automatic thumbnail generation Many web application frameworks and CMSs provide ways to automatically scale images for thumbnail and other sizes If programming in those environments, please be aware of what those technologies are and make sure to utilize them accordingly For instance, with our example, we could use the Python Image Library (PIL) to dynamically resize our large images for use in the gallery 57 www.it-ebooks.info Galleria How-to Existing application Galleria integrations Some CMSs already provide Galleria integration as follows: ff Plone: This is the Python based enterprise level CMS ‰‰ ff Wordpress: This is the blogging platform ‰‰ ff addon: http://plone.org/products/plone-true-gallery addon: http://wordpress.org/extend/plugins/photo-galleria/ Joomla: This is the PHP CMS ‰‰ addon: http://www.joohopia.com/joomla-modules/jgalleriamodule.html Search the addons of other platforms for Galleria to see if it's supported 58 www.it-ebooks.info Thank you for buying Instant Galleria How-to About Packt Publishing Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done Packt books are more specific and less general than the IT books you have seen in the past Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike For more information, please visit our website: www.packtpub.com Writing for Packt We welcome all inquiries from people who are interested in authoring Book proposals should be sent to author@packtpub.com If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise www.it-ebooks.info Ext JS Web Application Development Cookbook ISBN: 978-1-849516-86-0 Paperback: 488 pages Over 110 easy-to-follow recipes backed up with real-life examples, walking you through basic Ext JS features to advanced application design using Sencha's Ext JS Learn how to build Rich Internet Applications with the latest version of the Ext JS framework in a cookbook style From creating forms to theming your interface, you will learn the building blocks for developing the perfect web application Easy to follow recipes step through practical and detailed examples which are all fully backed up with code, illustrations, and tips Learning Ext JS ISBN: 978-1-849516-84-6 Paperback: 434 pages Sencha Ext JS for a beginner Learn the basics and create your first classes Handle data and understand the way it works, create powerful widgets and new components Dig into the new architecture defined by Sencha and work on real world projects Please check www.PacktPub.com for information on our titles www.it-ebooks.info Learning jQuery, Third Edition ISBN: 978-1-849516-54-9 Paperback: 428 pages Create better interaction, design, and web development with simple JavaScript techniques An introduction to jQuery that requires minimal programming experience Detailed solutions to specific client-side problems Revised and updated version of this popular jQuery book jQuery 1.4 Reference Guide ISBN: 978-1-849510-04-2 Paperback: 336 pages A comprehensive exploration of the popular JavaScript library Quickly look up features of the jQuery library Step through each function, method, and selector expression in the jQuery library with an easy-to-follow approach Write your own plug-ins using jQuery's powerful plug-in architecture Please check www.PacktPub.com for information on our titles www.it-ebooks.info .. .Instant Galleria How -to Recipes to make you an expert user of the Galleria JavaScript framework Nathan Van Gheem BIRMINGHAM - MUMBAI www.it-ebooks.info Instant Galleria How -to Copyright... with any aspect of the book, and we will our best to address it www.it-ebooks.info www.it-ebooks.info Galleria How -to Welcome to Galleria How -to This How -to will guide you to become an expert. .. classic theme that comes with the Galleria source code How to it There are two ways by which we can load theme files into Galleria: The first is to use the Galleria API to load the theme JavaScript

Ngày đăng: 20/02/2014, 02:20

Từ khóa liên quan

Mục lục

  • Cover

  • Copyright

  • Credits

  • About the Author

  • About the Reviewer

  • www.PacktPub.com

  • Table of Contents

  • Preface

  • Galleria How-to

    • Setting up the development environment (Simple)

    • Your first gallery (Simple)

    • Configuring Galleria (Simple)

    • Installing themes (Simple)

    • Creating your own theme (Medium)

    • Creating mobile friendly themes (Simple)

    • Installing plugins (Simple)

    • Using the flickr plugin (Medium)

    • Creating a plugin (Advanced)

    • Using the API (Medium)

    • Alternative image data structures (Simple)

    • Optimizing Galleria (Simple)

Tài liệu cùng người dùng

Tài liệu liên quan