Wednesday, November 27, 2013

Intern Story: Begining Android Development (first hand experience)


Before starting developing Android apps, the development environment is set up. I found it a bit of a hassle, but once it sets up, it works really well. Eclipse is the IDE that I use. I am following the Android training from developer.android.com. Android applications are built in Java and uses XML. The first day is stressful as the vocabulary from the Java and the Android SDK is completely new to me. It takes time to understand and get acquainted with the new vocabulary.

The XML part is straight forward, but linking things like links in websites is a fiddly job. As we can make html pages in website for each page in an Android application we make an Activity. And we can link between activities like we can do in website, which can be done by intent. Intent is an intention to do an action. It is a message from an application saying it wants to perform an action. It lets the applications to interact with each activity and share data. This is a useful feature that helps to move swiftly between the activities, and notify application & user of various events. The activities we link to/from are capable to listen to the intents and respond to them.

The next chapter in developer.android.com is, I feel, not as good as the first because it does not give us the step by step guide of everything in detail. I felt the need to find some other tutorials which could be handy for a beginner like me where every small element is described with examples.

Layouts are the essential things to know when we start learning android. Android layouts are written in XML. It is a resource that defines what to see on the screen which organizes the child controls such as button or text controls or images. I found it easy to start building layouts in XML. There are a number of different layout types that can be used to organize controls on a screen and we can choose the appropriate layout in accordance with our requirement. Layouts can be nested if needed.

I can use the style resource to define the format and look for a UI and the style can be applied to an individual View or to an entire Activity or application. Android uses XML for styles. Android also uses XML for strings, colors and others. A string resource provides text strings for application with optional text styling and formatting.

What I came to know as a thing of vital importance is Android development platform helps to make the application work itself across all the devices with wide variety of resolution, screen sizes, and screen densities by performing scaling and resizing to give user the feeling that using android is one fluid experience. For this, all the images for different screen densities are saved in the drawable resources folder and the system will pick the correct one. The same thing can be done with the layouts, different layouts for small and large screens can be used, and system will use the right one, simply just to fit the screen.

Overall, I'm beginning to grasp Android quickly. I could grasp wee bit of everything I learned. So in my view, through self-learning, Android Development will be challenging and exciting task to do but not a problematic and impossible task. I think, this is the era for the android developers as more and more versatile and powerful smartphones are built on android platforms. We just have to clear our mind and have the “let’s just do it” attitude to self-learn to develop android applications. I do really enjoy working with Android, and will definitely continue to do so in the future.

Written By:Bibash Shrestha
Android Apps / Game Development Intern
After his first week @ first hand experience in Android development

Monday, July 29, 2013

Basic blogger template : just posts, absolutely minimum

Here's a basic form of blogger template that you can use to build other advanced template. I always wanted to bake my own custom themes and templates for blogger but there's no official documentation - actually there are but not that developer friendly ! Further, inspecting existing template source code it is very hard to derive what follows. I mean, there are definitely rules and syntaxes to follow in blogger template but looking at any downloaded template can be intimidating to beginners.

So, this is very minimal template i'm presenting here. Make template a xml doc, inspect header and meta tags. All CSS style rules inside - under CDATA (it's xml). And minimum requirement for a blogger template is there should be at least one b:section This basic template has one section which includes a blog posts widget. To learn more about how sections / widgets work together please refer to links at footer.

Notes for further work:  

1) JS can be troublesome. If nothing worked encode it or put the whole content inside script into CDATA.
2) Images needs to be hosted. 

3) All CSS needs to be in one page or host it somewhere separately.
4) All JS needs to be in one page or host it somewhere separately.
5) Imagine different kind of "page" types and different kind of layout / templates you'd like to render depending upon different URLs, and imagine all of this to be done in single page XML file. Holy Shit ! There sure gonna be loads of if and else blocks if this has to be achieved in one page.

Enjoy. And if this work helped you get started in developing/designing blogger templates, don't forget to link my gist or this post in your website somewhere :) i'd be glad.




Grab code from gits: https://gist.github.com/bhu1st/6105200
Template Code Below:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>

<b:include data='blog' name='all-head-content'/>
<link expr:href='data:blog.url' rel='canonical'/>

<b:if cond='data:blog.pageType == &quot;index&quot;'>
  <title><data:blog.pageTitle/></title>
<b:else/>
<b:if cond='data:blog.pageType != &quot;error_page&quot;'>
 <title><data:blog.pageName/> - <data:blog.title/></title>
<b:else/>
 <title>404 - <data:blog.title/></title>
</b:if>
</b:if>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="Semicolon developers, semicolon languages, semicolon technologies, semicolon software, developers network, network professionals, web development nepal, software development nepal, offshore development nepal, outsourcing nepal, web development kathmandu, software development kathmandu, offshore development kathmandu, outsourcing kathmandu, computer courses in kathmandu, PHP course , JavaScript course, android course, " />
<meta name="description" content="Semicolon developers network pvt. ltd. is an Android and web application development company in Kathmandu, Nepal. We can be your next IT development partner." />
 
<!-- You May Not Share any of these codes unless giving credits to Technolies blog -->
    <b:if cond='data:blog.pageType == &quot;archive&quot;'>
     <meta content='noindex,noarchive' name='robots'/>
    </b:if>  

<b:skin><![CDATA[/*
-----------------------------------------------
Blogger Template: Semicolon Developers
Template By:      Bhupal Sapkota
URL:              http://semicolondev.com
Date:             29 July 2013
----------------------------------------------- */
html, body{
background:#FFF;
margin:0;
padding:0;
}

]]></b:skin>

</head>

<body>


<b:section class='main' id='main' showaddelement='yes'>
<b:widget id='Blog1' title='Blog Posts' type='Blog' locked='false'>

<b:includable id='main' var='main'>

  <!-- blogposts -->

  <div>
    <b:loop values='data:posts' var='post'>
      <b:include data='post' name='post'/>
    </b:loop>      
  </div>

   <!-- navigation -->
  <b:include name='nextprev'/>

</b:includable>


<b:includable id='post' var='post'>
  <div class='post'>
    <a expr:name='data:post.id'/>

    <b:if cond='data:post.title'>
      <h2>
     <b:if cond='data:post.link'>
        <a expr:href='data:post.link'><data:post.title/></a>
     <b:else/>
        <b:if cond='data:post.url'>
          <a expr:href='data:post.url'><data:post.title/></a>
        <b:else/>
          <data:post.title/>
        </b:if>
     </b:if>
      </h2>
    </b:if>

<div class='post-meta'>
Posted by  <data:post.author/>, <data:post.dateHeader/>
</div>

<div>
<data:post.body/>
</div>

  </div>
</b:includable>

<b:includable id='nextprev'>
  <div>
    <b:if cond='data:newerPageUrl'>
      <a expr:href='data:newerPageUrl' expr:id='data:widget.instanceId + &quot;_blog-pager-newer-link&quot;' expr:title='data:newerPageTitle'>&#171; <data:newerPageTitle/></a>    
    </b:if>

    <b:if cond='data:olderPageUrl'>    
      <a expr:href='data:olderPageUrl' expr:id='data:widget.instanceId + &quot;_blog-pager-older-link&quot;' expr:title='data:olderPageTitle'><data:olderPageTitle/>  &#187;</a>    
    </b:if>

    <b:if cond='data:blog.homepageUrl != data:blog.url'>
      <a class='home-link' expr:href='data:blog.homepageUrl'><data:homeMsg/></a>
      <b:else/>
      <b:if cond='data:newerPageUrl'>
        <a class='home-link' expr:href='data:blog.homepageUrl'><data:homeMsg/></a>
      </b:if>
    </b:if>

  </div>

</b:includable>


</b:widget>                  
</b:section>


</body>
</html>



References:

Official Reference from Blogger:
Layouts: https://support.google.com/blogger/topic/12449?hl=en&ref_topic=1697868
Advance Use: https://support.google.com/blogger/topic/1711140?hl=en&ref_topic=1697868
Next Level tips: https://support.google.com/blogger/answer/3059863?hl=en&ref_topic=1697868

Follow these in order:
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-blogger.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-body-and.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-header.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-inside.html
http://www.thesimplexdesign.com/2011/08/how-to-make-blogger-template-how.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-body-and.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-data-tags.html
http://www.thesimplexdesign.com/2011/07/how-to-make-blogger-template-data-tags_27.html


Wednesday, January 23, 2013

Implementing dual language feature in PyroCMS/CI?


Implementing dual language (multilingual / multi language) feature in CodeIgniter based PyroCMS?
Our Language Requirements : English / Nepali 

Semicolon Developers are in trouble. All clients we have now are requesting websites in Nepali and English language. CodeIgniter and most of all CodeIgniter based PyroCMS has been our choice of development tool since a long time. Check other posts on echo and you’ll know what I am talking about.

PyroCMS or CI as is are designed to support multilingual feature. But we have yet to figure out what is the best and effective way to implement this.

For now, given the urgency of feature request of our client and our commitment to project deadline we did a little hack for supporting two language in PyroCMS as follows:

General UI and widget blocks or different “titles” are easy to translate by using the default CI Language Class refer here and here for CI.


1) We stored default language in session or initially session could be blank.
2) We used two links to switch language in frontend.

{{ if {session:data name="language"} == 'np' }}
<li><a href="{{ url:site }}language/en">EN</a></li>
{{ else }}
<li><a href="{{ url:site }}language/np">NP</a></li>
{{ endif }}

the /language controller does the magic !

3) Now for the navigation links we created two navigation groups and switched depending upon the language value stored in session.

{{ if {session:data name="language"} == 'np' }}
{{ navigation:links group="header_np" }}
{{ else }}
{{ navigation:links group="header" }}
{{ endif }}   



4)  /language/en or /language/np  can be routed to a function through routes. A function can be used to get specific segment of the url . When it is fetched the necessary session modification can be done on function as:

This modification is done on the session variable (here language)
Finally routing to the base url page as per required

//...controller code
public function language($lang){

if($lang=="en" || $lang=="np") {
$this->session->set_userdata(array('language' => $lang));
}
redirect(base_url());
}

This operation is intended for dual language and can be extended further with required conditional statements.

FYI, this is not a perfect way to build multilingual feature. Problem can arise while dealing with more than two languages. If you have better solution let us know.



Sunday, November 18, 2012

My First take on PyroCMS


What is PyroCMS ?

PyroCMS is a open source framework for content management system created with standard PHP/MVC framework CodeIgniter. It is light and simple to use and is for both the developers and the end users. Generally it is used for websites which contains large amount of content/articles. The content should be well presented to the user for displaying as per requirement . This is where pyrocms comes which can manage the display of those content as per requirement.


How PyroCMS can be customized to develop websites on it ?

PyroCMS provide the dashboard for administration section to be used for developing big content based websites easily.
As it provides various tools/modules for implementing the website design and functionality which are very necessary for the a perfect websites.

Modules such as:

Navigation: It is used for the navigate through out website links.
Blog: This is used for the articles to be posted like blogs, also they can be well surfed by the end users.
Comment: Users and guests can write comments for content published and share their views.
Pages: Add pages to the site with content that are mostly static or vary in time.There are many other modules that can used


Why PyroCMS is better than Wordpress, Drupal and other existing CMSes ?

All of the CMSes have not any fixed and standard framework for using it. Therefore it will be difficult for different developers to interact with various created sites. With pyro we are developing a cms with customized outlook and standard framwork which can be very developer friendly.

What can we do with PyroCMS ?

Being small and flexible, PyroCMS can be very usefull to small and to large content based sites.


What are PyroCMS Themes ? 

Themes are the outlook that are presented to users. It contains the design that can be navigated by the users. PyroCMS provides suitable method to develop the themes. PyroCMS contains main layout and the partials files that make up the single website theme.


How to build PyroCMS themes ?

In PyroCMS Theme are structured in different folders like css for stylesheets files, js for javascripts and views for overall structure of the website. In views folder the main design is kept inside layouts which is the central look . The designs are splitted within the folder called partials which contains the design units like header, footer, sidebar etc.  Also necessary information about the theme and the screenshot is also included for informations.


Lastly, using Pyrocms was very fun to use. It is more similar to CodeIgniter therefore people comfortable with codeIgniter may find it very easy to use. Also it is very useful for customizing our desired look and functionality. Also we should use it very calmly. Despite of few documentations and support i am sure user/develop would find it very handy. 
 

Monday, November 12, 2012

Android asynchronous/synchronous HTTP request

 

////////////////////////OBHttpClient.java /////////////////

package com.semicolondev.baghchal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.os.Handler;
import android.util.Log;

public class OBHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 60 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private HttpClient mHttpClient;
    /** Asynchronous request handler */
    private Handler mHandler;
    public static int METHOD_GET = 1;
    public static int METHOD_POST = 2;
    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP synchronous request to the specified url with the
     * specified parameters of get or post.
     * @param method GET or POST method
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request for POST request – null for GET request
     * @return The result of the request as a string
     * @throws Exception
     */
    public String OBrequestHttp(int method, String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            if(method == METHOD_GET){
                HttpGet request = new HttpGet();
                request.setURI(new URI(url));
                HttpResponse response = client.execute(request);
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            }
            else if(method == METHOD_POST){
                HttpPost postrequest = new HttpPost(url);
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
                postrequest.setEntity(formEntity);
                HttpResponse postresponse = client.execute(postrequest);
                in = new BufferedReader(new InputStreamReader(postresponse.getEntity().getContent()));
            }
            else{
                return "INVALID METHOD";
            }
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            //Log.d("Login Response", result);
            return result;
        } catch(Exception e){
            return "REQUEST ERROR";
        }
            finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

/**
     * Performs an HTTP asynchronous request to the specified url with the
     * specified parameters of get or post.
     * @param method GET or POST method
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request for POST request – null for GET request
     * @type which url the request has suggested

     * @obaction result send back to the activity

    * @return The result of the request as a string
     * @throws Exception


     */


    public void OBrequestAsyncHttp(final int method, final String urls,final OnlineGameView.url_enumb type,final ArrayList<NameValuePair> formParams,final OBActionResult obaction) {
        if (mHandler == null){
            mHandler = new Handler();
        }
        //Log.i("OB","Thread started for url = " + urls);
        new Thread(new Runnable() {
            public void run() {
                final String restResponse;
                restResponse = requestposturl(method, urls, formParams);
                mHandler.post(new Runnable() {
                    public void run() {
                        obaction.completedWithResult(type, restResponse);
                        //Log.i("OB","Result sent");
                    }
                });
            }

            private String requestposturl(int method, String urls, ArrayList<NameValuePair> formParams) {
                try{
                    //Log.i("OB","Url = " + urls);
                    String response = OBrequestHttp(method,urls, formParams);
                    return response;
                }
                catch(Exception e){Log.i("OB","Something error");return "";}
            }
        }).start();
}
}

 

///////////////OOActionResult.java ///////////////////

package com.semicolondev.baghchal;

public interface OBActionResult {
    public void completedWithResult(String type, String response);   
}

 

////////////////////////mainActivity.java/////////////

public class mainActivity extends Activity implements OBActionResult{

//the request should be done by

OBHttpClient obclient = new OBHttpClient();
        obclient.OBrequestAsyncHttp(OBHttpClient.METHOD_GET, “http://localhost/query”, “login”, null, this);

// and the result will be collected in

@Override
    public void completedWithResult(String urlfrom, String response) {
        Log.i("OB","url = "+urlfrom+" data = " + response);

}

}

Wednesday, November 7, 2012

Android Simple Login Dialogue Box

package com.semicolondev.baghchal;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public abstract class test extends Activity
{

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.login, null);
final EditText userText = (EditText) textEntryView.findViewById(R.id.login_userID);
final EditText passText = (EditText) textEntryView.findViewById(R.id.login_password);
AlertDialog.Builder builder = new AlertDialog.Builder(this);  
AlertDialog alert;
builder.setMessage("Enter Username and Password")
.setCancelable(true)
.setView(textEntryView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i("OB","Logging in ..");
try{
String url = "http://192.168.1.16/api/login?userID="+userText.getText().toString().trim()+"&password="+passText.getText().toString().trim();
Log.i("OB","url= "+url);
String response = OBHttpClient.executeHttpGet(url);
Log.i("OB","Response="+response);              // if valid login response ={"res":"success"}
JSONObject resObj = new JSONObject(response);
String resServer = resObj.getString("res");
if(resServer.equals("success")){
Toast.makeText(this,"Login Success", Toast.LENGTH_LONG).show();
Log.i("OB","Success");
}
else{
Toast.makeText(this,"Login Failed", Toast.LENGTH_LONG).show();
Log.i("OB","Invalid");
}
}catch(Exception e){Toast.makeText(this,"Sorry", Toast.LENGTH_LONG).show();}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {                                                 
}
});
alert = builder.create();
alert.show();

}
}

.... login.xml ....
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip">
<!--  Email Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Username"/>
<EditText android:id="@+id/login_userID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="20dip"
android:singleLine="true"/>
<!--  Password Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Password"/>
<EditText android:id="@+id/login_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:password="true"/>
</LinearLayout>

Tuesday, November 6, 2012

Android HttpClient- Parse JSON


JSON from server:

{"res":"success","click":{"value":[0,2,1,1,1,1,0,2,1,1,1,1,1,0,5,2,1,1,0,0,1,1,1,1,7],"gameID":"5098fac4c96d664f690079d2","turn":"winBagh","goat_count":20,"dead_goat":5,"timestamp":"1352203321097","_id":"5098fc39c96d664f69007a41"}}

try{
postParameters= new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("gameID", online_gameID));
String response = OBHttpClient.executeHttpPost("http://192.168.135.136/json", postParameters);

JSONObject resObj = new JSONObject(response);
Log.i("OB","resObj = " + resObj  );
String resServer = resObj.getString("res");
Log.i("OB","resServer = " + resServer  );

if(resServer.equals("error")){
Toast.makeText(ctx,"Wait for other user move", Toast.LENGTH_LONG).show();
    return false;
}
else{

JSONObject clickObj = resObj.getJSONObject("click");
Log.i("OB","clickObj = " + clickObj  );
String value = clickObj.getString("value").replace("[", "").replace("]", "");
String[] coord = value.split(",");
int[] orgval = new int[25];
for(int i=0; i<25 ; i++)
orgval[i] = Integer.parseInt(coord[i]);
//click.setGameValue(orgval);
click.setClicks(orgval, ((clickObj.getString("turn") == "goat")? 1 : 2), clickObj.getInt("dead_goat"), clickObj.getInt("goat_count"));//, clickObj.getString("timestamp"), clickObj.getString("gameID"));
return true;

}
}
catch(Exception e){
    Toast.makeText(ctx,"Error", Toast.LENGTH_LONG).show();
}

Tuesday, November 8, 2011

PyroCMS Themes, Widgets & Modules samples + tutorials


Themes :

https://github.com/semicolondevelopers/pyro_theme_artificial_casting
https://github.com/semicolondevelopers/pyro_theme_blue_spades
https://github.com/semicolondevelopers/pyro_theme_business_time
https://github.com/semicolondevelopers/pyro_theme_coffee
https://github.com/semicolondevelopers/pyro_theme_eco_design
https://github.com/semicolondevelopers/pyro_theme_night_club

PyroCMS v1.3.2 Theming Guide for beginners:
http://echo.semicolondev.com/2011/11/hot-to-create-pyrocms-v132-theme-step.html

PyroCMS Tag Cheat Sheet
http://techmix.net/blog/2011/10/23/pyrocms-tag-reference-cheat-sheet/

Widgets

https://github.com/semicolondevelopers/pyro_widget_category
https://github.com/semicolondevelopers/pyro_widget_login_box
https://github.com/semicolondevelopers/pyro_widget_selected_category_posts

PyroCMS v1.3.2 Widget creation guide for beginners
http://echo.semicolondev.com/2011/11/how-to-create-pyrocms-v132-widgets.html

Modules:

Hello World Module
https://github.com/semicolondevelopers/pyro_module_hello

Old 0.9.9.x Forum module upgraded to v1.3.2
https://github.com/semicolondevelopers/pyro_module_forums

PyroCMS v1.3.2 & v0.9.9.7 Module Creation guide for beginners:
http://bhu1st.blogspot.com/2010/09/hello-world-pyrocms-module.html

Monday, November 7, 2011

Hot to create PyroCMS v1.3.2 Theme/ Step by step PyroCMS Theming Guide


A quick guide for creating PyroCMS Theme from a normal HTML / CSS template

Get any HTML /CSS template & follow the steps below!!

We prefer:
http://www.freecsstemplates.org
http://www.oswd.org

1. Install PyroCMS.

2. Go to installation folder -> addons -> shared_addons -> themes

3. There are two pre built themes. Copy either “minimal” or “conjuction” folder & paste it .

4. Here, we’ll use folder “minimal” . You’ll now see a new folder named “Copy of minimal”.

5. Rename it with the new theme name as u like. I’ll name it “tutorial”

6. Open the folder .

7. Open file “theme.php” in notepad++ or any other IDEs.

8. In the file

Replace “ class Theme_Minimal extends Theme “ with “class Theme_Tutorial extends Theme “

PTR : Old theme folder’s name must be replaced with the new folder name u gave to it. The first letter of name should begin with the capital letter.

clip_image001

Replace the text in between the single quotation mark as relevant.

Save & close the file.

9. Delete all the files in CSS folder & put the css file of ur new template in that folder.

10. Goto folder “views” -> then folder “layout”. There is a file “default.html” which is supposed to be like “index.html” of HTML/CSS template.

11. Open “default.html” in editor.

12. Also open the index.html file of downloaded template in editor.

13. Copy all the content of “index.html” in to the “default.html” after removing the initial content of “default.html” .

14. Replace CSS linking code in head section

<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" />

With

{pyro:theme:css file=”your_css_filename.css”}

15. If u hav javascript file in templates…create JS folder in “Tutorial” folder & paste inside it..

16. Linking Js file from head section

{pyro:theme:js file=”filename.js”}

In case u hav multiple files…use same code multiple times bt the order of js/css should occur as it is in template head section

17. Now..we break down the file “default.html” into multiple files.

18. All broken mini files are called partials and they should be kept in folder “partials”.

19. Let’s check the breaking process..

20. Create a new file named “metadata.html” & then cut the code inside <head> tag & paste it to “metadata.html”.save the file in folder “partials”.

21. Create a new file named “nav.html” & then cut the code inside <head> tag & paste it to “metadata.html”.save the file in folder “partials”.

22. You can cut contents in side the <div> tags as well.

Suppose: default.html has following code

<div class=”nav”>
<ul>
<li>home</li>
<li>contact</li>
</ul>
</div>

Cut the contents inside <div></div> tag and paste it to new file & name it “nav.html” & save it to “partials” folder

23. Similarly break other codes from default.html file & save to partials.

24. Now we learn to link the files in folder”partials” so that the code we broke is included in default.html.

In head section

<head>

{pyro:theme:partial name=”metadata”}

</head>

In <div> tag

<div class=”nav”>

{pyro:theme:partial name=”nav”}

<div/>

25.Now we learn to use images in the theme we working for.

26. copy the folder “images” from the downloaded template & paste it to the theme folder.

27.check CSS file & find the images it has been using..then cut all images from folder “images” except those being used by css file & paste it to new folder named “img”.

28.replace the code in other files.
initial code :- <img src=”button.png” alt=”submit”/>

New code :- {pyro:theme:image file=”button.png”}

29. to get the navigation menu set by from the admin panel in certain div

<div class=”menu_bar”>

{pyro:navigation:links group=”header”}

</div>

30. to get the content set by admin (dynamic content) in any div
<body>

<div class=”main_content”>

{pyro:template:body}

</div>

There go you. Your PyroCMS Theme is now ready to be used.

For Code Visit our Github page:
https://github.com/organizations/semicolondevelopers

Tutorial by:
Prajwol Shrestha
Semicolon Developers

How to create PyroCMS v1.3.2 widgets ?

 

A quick guide for creating new widget in PyroCMS.

1. Go through these folders
CMS_installed_folder -> system -> cms -> widgets

2. All these folders are for separate widgets.copy anyone. We’ll use it as reference to create a new widget.

3. Paste that folder in
CMS_installed_folder -> addons -> shared_addons -> widgets

4. Here suppose I copied “navigation” widget folder & pasted.

5. There is folder name “views” & a file named “navigation.php”

6. Two more files inside “views” folder ..named “display.php” & “form.php”. “Display.php” is for frontend

7 “form.php” is for control panel.

7. Every widgets should hav the above mentioned folder & files bt with the name according to ur requirement.

8. Now we edit the files in the folder we pasted.

9. Suppose we are displaying categories via this widget.

10. Rename the folder to ”category”.

11. Rename file navigation.php to category.php.

12. Open category.php in text editor.

clip_image002

13. Rename Widget_navigation to Widget_Category. The replaced text should contain the name of ur file u r editing & name must begin wid the capital letter.

14. ‘en’ , ‘pt’ ,’ru’ etc are the languages..so u can delete them except “en” . en is the English language..

15. Replace text ‘en’ => ‘navigation’ with ur widget name. ‘en’ => ‘category’ in title array.

16. Replace text ‘en’ => ‘Display a navigation group with a widget’ with ‘en’ =>’description of ur widget’.

17. Change value of $author,$website & $version as u wish.

18. image The $fields is the array of fields that will be appearing in the form for control panel & passing the value while calling a function.

Here, run function is for running the query. If input has been taken from form in the control panel ,then the parameters should be passed to the function with variable “$options” else it will be just run(). We fetch an array in $options from the from in control panel.

19. U hav to load the model file which contains the database query u require. Or u can create your own model with reference of old model. If u dnt want to create new model..u have to add a function that can return the require the data from database in it.

20. That function called from run function and returns the array data to run function.

21. Run function returns it to display.php & this file renders the content to front end.

22. Grab the array in display.php & use it to display the require contents.

To install the widget :

1. Goto admin panel.image

2. 

Content -> widgets -> drag & drop widgets from list to the available areas.

3. Copy the code {pyro:widgets:instance id=”3”} & paste it the front end html file where u wud like the widget’s content to be displayed.

For Code Visit our Github page:

https://github.com/organizations/semicolondevelopers

Tutorial by:
Prajwol Shrestha
Semicolon Developers

 

© 2013 Echo "Semicolon Developers"; Kathmandu. All rights resevered @ Semicolon Developers Network Pvt. Ltd.. Designed by Templateism

Back To Top