![]() |
BerryReview |
La mala es que Twitter -siguiendoel calendario previsto por cierto- ha dejado de dar soporte a la API 1 que hasta ahora sustentaba una gran parte de los gadgets que permitían mostrar un timeline determinado de una manera personalizada (1) (2).
La siguiente, sólo regular, es que ahora hay que pasar por taquilla -es un decir- y para construir un gadget de Twitter hay que hacerlo por narices desdesu página oficial previa autentificación.
Otra de igual enjundia es que desde allí sólo se pueden generar gadgets oficiales, todos grandísimos y casi nada configurables en cuanto a estética por tratarse de iframe's.
Y por fin la buena: Alguien ha tenido una idea feliz para poder solventar todo esto y ha creado un código bastante bueno que da mucho juego.
Ese alguien esJason Mayes y fue ayer mismo cuando tropecé con su página y con esteJSFiddle dónde se puede ver que todo funciona correctamente.
Esta vez no voy a explicaros con detalle que hace todo eso porque hay bastantes cosas más que comentar, pero básicamente hace uso de los widgets oficiales recortando todo lo que "sobra" y dejando sólo lo que interesa: avatar, nick, usuario, mensaje y fecha. Veamos cómo ponerlo en nuestro sitio.
1. Incluir el código principal
Este es ese código y sólo es necesario conservar los créditos del principio para poder usarlo. Atentos a las últimas líneas (// Ejemplos) que será lo único que habrá que modificar como después veremos. En Blogger lo podéis añadir como gadget tipo HTML/JavaScript.
// #### Twitter Post Fetcher v7.0 ####
// Coded by Jason Mayes 2013 www.jasonmayes.com
var twitterFetcher=function(){function t(d){return d.replace(/b[^]*(.*?)\/b/gi,function(c,d){return d}).replace(/class=".*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,"")}function m(d,c){for(var f=[],e=RegExp("(^| )"+c+"( |$)"),g=d.getElementsByTagName("*"),b=0,a=g.length;ba;b++)e.test(g[b].className)&&f.push(g[b]);return f}var u="",j=20,n=!0,h=[],p=!1,k=!0,l=!0,q=null,r=!0;return{fetch:function(d,c,f,e,g,b,a){void 0===f&&(f=20);void 0===e&&(n=!0);void 0===g&&(g=!0);void 0===b&&(b=!0); void 0===a&&(a="default");p?h.push({id:d,domId:c,maxTweets:f,enableLinks:e,showUser:g,showTime:b,dateFunction:a}):(p=!0,u=c,j=f,n=e,l=g,k=b,q=a,c=document.createElement("script"),c.type="text/javascript",c.src="//cdn.syndication.twimg.com/widgets/timelines/"+d+"?&lang=en&callback=twitterFetcher.callback&suppress_response_codes=true&rnd="+Math.random(),document.getElementsByTagName("head")[0].appendChild(c))},callback:function(d){var c=document.createElement("div");c.innerHTML=d.body;"undefined"===typeof c.getElementsByClassName&&(r=!1);var f=d=null,e=null;r?(d=c.getElementsByClassName("e-entry-title"),f=c.getElementsByClassName("p-author"),e=c.getElementsByClassName("dt-updated")):(d=m(c,"e-entry-title"),f=m(c,"p-author"),e=m(c,"dt-updated"));for(var c=[],g=d.length,b=0;bg;){if("string"!==typeof q){var a=new Date(e[b].getAttribute("datetime").replace(/-/g,"/").replace("T"," ").split("+")[0]),a=q(a);e[b].setAttribute("aria-label",a);if(d[b].innerText)if(r)e[b].innerText=a;else{var s=document.createElement("p"), v=document.createTextNode(a);s.appendChild(v);s.setAttribute("aria-label",a);e[b]=s}else e[b].textContent=a}n?(a="",l&&(a+='div class="user"'+t(f[b].innerHTML)+"/div"),a+='p class="tweet"'+t(d[b].innerHTML)+"/p",k&&(a+='p class="timePosted"'+e[b].getAttribute("aria-label")+"/p")):d[b].innerText?(a="",l&&(a+='p class="user"'+f[b].innerText+"/p"),a+='p class="tweet"'+d[b].innerText+"/p",k&&(a+='p class="timePosted"'+e[b].innerText+"/p")):(a="",l&&(a+='p class="user"'+f[b].textContent+ "/p"),a+='p class="tweet"'+d[b].textContent+"/p",k&&(a+='p class="timePosted"'+e[b].textContent+"/p"));c.push(a);b++}c.lengthj&&c.splice(j,c.length-j);d=c.length;f=0;e=document.getElementById(u);for(g="ul";fd;)g+="li"+c[f]+"/li",f++;e.innerHTML=g+"/ul";p=!1;0h.length&&(twitterFetcher.fetch(h[0].id,h[0].domId,h[0].maxTweets,h[0].enableLinks,h[0].showUser,h[0].showTime,h[0].dateFunction),h.splice(0,1))}}}();
function dateFormatter(date) {return date.toTimeString();}
// Ejemplo con 3 tuits a insertar en un elemento con id='tweets' con enlaces activos
twitterFetcher.fetch('347121215158222848', 'tweets', 3, true);
// Ejemplo con 5 tuits a insertar en eun elemento con id='tweets2' con enlaces activos, sin detalles de usuario, con fecha y usando un formato personalizado para la fecha
twitterFetcher.fetch('347118235830870017', 'tweets2', 5, true, false, true, dateFormatter);
// Ejemplo con 1 tuit a insertar en un elemento con id='tweets3' con enlaces activos, sin detalles de usuario ni fecha
twitterFetcher.fetch('347086380704342017', 'tweets3', 1, true, false, false);
/script
2. Relacionar con el gadget oficial
Ahora los datos no se pueden generar de manera independiente y hay que obtenerlos desde un widget oficial. Para vincularlo con este script utilizamos ese número largo al principio de cada funcióntwitterFetcher. Aparecen al final del código principal y los he marcado en verde, al igual que el resto de parámetros configurables. Se trata de un identificador que os asigna Twitter cuando creáis un widget con su sistema. Para generarlo y localizarlo sigue estos pasos:
- validado en Twitter, crea un widget desde https://twitter.com/settings/widgets
- crea un nuevo widget con lo que necesites, cronología, favoritos, etc.
- si no quieres incluir las respuestas asegúrate de marcar su exclusión
- pincha en el botón "Volver a la configuración del widget" y en la nueva pantalla pincha en "Editar"
- ahora fíjate en la dirección de tu navegador, ahí tienes la id del gadget, entre /widgets/ y /edit
- tal que aquí: https://twitter.com/settings/widgets/XXXXXXXXXXXXXXXXXX/edit
Una vez lo tengáis, no olvidéis cambiarlo en el código principal. Se pueden poner tantos distintos como se quiera y ya habéis visto que yo incluí tres, aunque lo normal será dejar una sola de esas tres funciones con la configuración exacta que necesitamos.
3. Añadir una caja vacía para que sea visible
Una vez el código esté en vuestro sitio sólo hay que poner una caja vacía con laid que hayamos elegido (en los ejemplostweets,tweets2 ytweets3) y el script se encargará de insertar en ella lo que hayamos programado en las últimas líneas.
Así, siguiendo los tres ejemplos que puse, dónde añadamosdiv id="tweets"/div nos saldrá algo así:
Condiv id="tweets2"/div obtendremos otro tipo de datos.
Y finalmente condiv id="tweets3"/div esto otro, un tuit simple:
Parámetros de la función twitterFetcher
Ejemplo 2:twitterFetcher.fetch('347118235830870017', 'tweets2', 5, true, false, true, dateFormatter);
Así tal cual lo puse, el código os mostrará uno de los formatos de datos que yo utilicé según uséis unaid u otra, pero también eso lo podéis personalizar. De la serie de parámetros separados por comas sólo los dos primeros son obligatorios, el identificador del widget y la id de la caja dónde meteremos el resultado. Los demás son opcionales y en este orden serían:
- el número máximo de tuits a mostrar, desde 1 a 20 (por defecto 20)
- true/false según queramos que nicks, URL's y hashtags tengan enlaces o no (por defecto false)
- true/false para que se muestre el avatar, nick y el usuario (por defecto true)
- true/false para mostrar fecha/hora del tuit (por defecto true)
- nombre de la función que convertirá la fecha al formato que quieras (por defecto saldrá el formato Twitter)
Para personalizar la hora y fecha puedes definir una función que tome una fecha JavaScript como parámetro y devuelva una cadena. En el ejemplo se incluyó una llamadadateFormatter.
Estilo CSS
Pero como además de querer personalizar los datos de salida, posiblemente también os interese personalizar la estética, aquí tenéis la lista de selectores que vais a necesitar. He supuesto que utilizaréis la idtweets. Para otra id habría que sustituir ese nombre.
#tweets * {}
/* Bloque del gadget */
#tweets {}
/* Lista de tuits */
#tweets ul {}
/* Cada uno de los tuits */
#tweets li {}
/* Bloque datos usuario */
#tweets .user a {}
/* Avatar */
#tweets .user img {}
/* Nick */
#tweets .user a span {}
/* Usuario Twitter */
#tweets .user span + span {}
/* Cuerpo texto del tuit */
#tweets p {}
/* Enlaces en el tuit */
#tweets p a {}
/* Fecha */
#tweets p.timePosted {}
Las reglas que he utilizado para las salidas que visteis en el post fueron estas:
#tweets {margin: 20px 0; text-align:center;}
#tweets ul {display: inline-block; width: 80%; list-style:none; clear:both;}
#tweets li {margin-bottom: 5px; text-align: left; clear:both;}
#tweets .user a {float:left; width:120px;}
#tweets .user img {float: left; width: 80px;}
#tweets .user a span {display:none;}
#tweets .user span + span { display:block; margin-top:10px;font-size: 9px;}
#tweets p.timePosted {font-size: 80%;}
#tweets2 {margin: 20px 0;}
#tweets2 ul {list-style:none; clear:both;}
#tweets2 li {display: block; margin-bottom: 5px; padding:5px; border: 1px solid #ccc; clear:both;}
#tweets2 p {font-size: 14px;}
#tweets2 p.timePosted {font-size: 80%;}
Al tuit simple no le asigné ningún estilo así que por defecto tomó las reglas generales de la página.
Y bien, a ver si saco otro rato para daros hecho el código con el que montar aquelcacharrito para mostrar tu último tweet que a muchos os ha dejado de funcionar por este motivo.
Donate Car To Charity CALIFORNIA DONATE CAR FOR TAX CREDITDONATE CARS IN MADONATE YOUR CAR SACRAMENTOHOW TO DONATE A CAR IN CALIFORNIA DONATE YOUR CAR FOR KIDS,CAR INSURANCE QUOTES COLORADO ,NUNAVUT CULTURE,DAYTON FREIGHT LINESHARDDRIVE DATA RECOVERY SERVICES,DONATE A CAR IN MARYLAND,MOTOR REPLACEMENTS,CHEAP DOMAIN REGISTRATION HOSTING,DONATING A CAR IN MARYLANDNos ofrece Mundial Football eloan com, FIFA World Cupuna gran variedad para contratar mesothelioma info y obtener un equity line of credit y una buena estructura de negocio SEO consolidate loans y visitar su casa matriz Mesothelioma law firm,home equity loans domain name searchSelling annuity payments for cash,Sell my structured settlement,Sell structured settlement,Structured settlement,Structured settlement companies,Sell my annuity payments lump sum,Car accident lawyer Denver,Accident injury attorneys,Sell my annuity
MESOTHELIOMA LAW FIRMDONATE CAR TO CHARITY CALIFORNIAHARDDRIVE DATA RECOVERY SERVICESDONATE A CAR IN MARYLAND DONATING A CAR IN MARYLAND,DONATE CARS ILLINOIS,CRIMINAL DEFENSE ATTORNEYS FLORIDA ,BEST CRIMINAL LAWYER IN ARIZONASTRUCTURED ANNUITY SETTLEMENT,ASBESTOS LAWYERS,NUNAVUT CULTURE,DAYTON FREIGHT LINES ,Bextra Bankruptcy Dental Plan Private JetMundial Football DONATE CAR TO CHARITY CALIFORNIA FIFA World Cup,DONATE CAR FOR TAX CREDIT, and DONATE CARS IN MA,DONATE YOUR CAR SACRAMENTO,HOW TO DONATE A CAR IN CALIFORNIA, SELL ANNUITY PAYMENT and DONATE YOUR CAR FOR KIDS,ASBESTOS LAWYERS pero for you STRUCTURED ANNUITY SETTLEMENT ,ANNUITY SETTLEMENTS, CAR INSURANCE QUOTES COLORADO and future now NUNAVUT CULTURE and pero mas aya del visita DAYTON FREIGHT LINES and Mesothelioma law firm HARDDRIVE DATA RECOVERY SERVICES,Selling annuity payments for cash,Sell my structured settlement,Sell structured settlement,Structured settlement,Structured settlement companies,Sell my annuity payments lump sum,Car accident lawyer Denver,Accident injury attorneys,Sell my annuity
Php programmers los angeles auto accident attorneys HOME PHONE INTERNET BUNDLE california motorcycle accident lawyer Car Insurance Companies Online casino Dallas Mesothelioma Attorneys motor insurance quotes Donate Your Car Sacramento small business administration sba New social media platforms motorcycle accident lawyer california Business finance group utah mesothelioma lawyer Hire php programmers CAR INSURANCE QUOTES PA bus accident attorney los angeles ASBESTOS LAWYERS Asbestos Lawyers EMAIL BULK SERVICE MESOTHELIOMA LAW FIRM personal injury solicitor mesothelioma care Business management software car accident lawyer michigan refinance with poor credit mesothelioma lawyer california Sell Annuity Payment structured settlement brokers Donate a car in Maryland firm law mesothelioma new york mesothelioma law firm Dwi lawyer alcohol rehab center in florida integrated ehr Bankruptcy lawyer Insurance mesothelioma lawyer chicago Donate a Car in Maryland Psychic for free Car Insurance Quotes Colorado Donate your Car for Money Live casino city college in miami best criminal lawyer in arizona asbestos mesothelioma lawsuit Hire php developer Casino Mesothelioma Law Firm Mobile casino Service business software mesotheloma data recovery raid MOTOR REPLACEMENTS Make money online Australia Best social media platforms for business google adsense miami personal injury attorney Social media campaigns selling my structured settlement Forensics Online Course Casino reviews See more at http//wwwginfostopnet/ paperport promotional code Tech school Motor Replacements forensics online course Italian cooking school motorcycle accident attorney chicago HOW TO DONATE A CAR IN CALIFORNIA mesotheolima mesothelioma claims DUI lawyer Hire php developers Psd to html anti spam appliance injury lawyers west palm beach st louis mesothelioma attorney structured annuity settlement federal criminal defense attorney Paperport Promotional Code Social media platforms for business World trade center footage NEUSON Low Credit Line Credit Cards Better conferencing calls Best Seo company Criminal lawyer Massage School Dallas Texas buying an annuity calculator Criminal defense lawyer Hard drive Data Recovery Services mesothelioma attorney Personal Injury Lawyer Php programmers for hire Personal Injury Law Firm mesothelioma ct Social media examiner mesothelioma lawyer dallas philadelphia mesothelioma lawyer ONLINECLASSES hosted predictive dialers Computer science classes online ONLINE COLLEDGES annuity payment Online College Course Social media platforms LOW CREDIT LINE CREDIT CARDS Seo companies Donate Car to Charity California personal injury accident lawyer donate your car for kids Photo Christmas cards NUNAVUT CULTURE earthlink business internet Home Phone Internet Bundle Royalty free images stock Mortgage Adviser Psd to WordPress Auto Accident Attorney colorado mesothelioma lawyers DONATE YOUR CAR SACRAMENTO Custom WordPress theme designer Seo services hair removal washington dc structured settlement company SELL ANNUITY PAYMENT webex costs Online Stock Trading low credit line credit cards Best social media platforms Seo company email bulk service Online Christmas cards verizon sip Custom Christmas cards WordPress themes for designers workers compensation lawyer los angeles WordPress hosting Best criminal lawyer in Arizona Adobe illustrator classes Social media management Car Insurance Quotes Online Criminal Justice Degree CAR ACCIDENT LAWYERS register free domains Cheap Car Insurance in Virginia Donate Cars Illinois Html email Forensics online course CHEAP AUTO INSURANCE IN VA home phone internet bundle Christmas cards Proud Italian cook WORLD TRADE CENTER FOOTAGE WordPress theme designers injury attorney baton rouge AUTO ACCIDENT ATTORNEY Social media strategies canada personals yahoo Learning adobe illustrator washington mesothelioma attorney mesothelioma settlements amounts Social media tools alabama mesothelioma lawyer donating used cars to charity World Trade Center Footage injury lawyers motor replacements Dayton freight lines DONATE CARS ILLINOIS Donate Car for Tax Credit Donate Cars in MA Nunavut culture Data Recovery Raid How to Donate A Car in California car donate Donate Your Car for Kids criminal defense attorneys florida Cheap Domain Registration Hosting Structures Annuity Settlement Donate your car Sacramento Online Colleges business administration masters Annuity Settlements Nunavut Culture adverse remortgage CAR INSURANCE QUOTES UTAH Car Accident Lawyers Dayton Freight Lines VIRTUAL DATA ROOMS Cheap domain registration hosting business voip solutions Car Insurance in South Dakota Futuristic Architecture Webex Costs structured settlemen Donating a Car in Maryland onlineclasses domain name yahoo buy gift card Criminal Defense Attorneys Florida Best Criminal Lawyers in Arizona supportpeachtreecom Car Insurance Quotes Utah Life Insurance Co Lincoln Holland Michigan College Online Motor Insurance Quotes motorcycle lawyer los angeles DONATE A CAR IN MARYLAND