Giter Site home page Giter Site logo

johannschopplich / kirby-vue3-starterkit Goto Github PK

View Code? Open in Web Editor NEW
209.0 7.0 19.0 15.67 MB

✨ Kirby + Vue SPA starter: automatic routing, i18n, SEO and more!

License: MIT License

Vue 30.62% JavaScript 25.68% PHP 39.51% CSS 2.98% Shell 1.20%
kirby a11y seo-friendly vuejs vitejs i18n

kirby-vue3-starterkit's Introduction

Note

Thank you to everyone who has used this starterkit in the past. I'm grateful that something built for myself has been useful to others. I have moved from Vue to Nuxt for my projects and will not be maintaining this starterkit actively anymore. It is stable, but be aware.

I recommend to check out Cacao Kit, which is the evolved version of this starterkit. It uses Nuxt and KQL with a headless Kirby setup. It is my best practice starterkit for your next project with server-side rendering. All features of this starterkit are included!


Logo of Kirby + Vue.js Starterkit

Kirby + Vue.js Starterkit

SPA with Vue 3 and Kirby: SEO-friendly, automatic routing, i18n and more!
Explore the starterkit live »


Kirby + Vue.js Starterkit

Key Features

Alternatives

SPA

  • kirby-vue-lightkit: ⛺️ Minimal Kirby + Vue starter: File-based routing, UnoCSS, SEO & more

SSR

Introduction

Or jump right to the setup.

This boilerplate is a tight and comprehensive integration of Vue.js in the frontend and Kirby as headless CMS. The content is provided as JSON through Kirby and fetched by the frontend.

Lighthouse report

Folder Structure

Some notes about the folder structure with some additional comments on important files.

Expand folder tree
kirby-vue3-starterkit/
|
|   # Main entry point of the website, point your web server to this directory
├── public/
|   |
|   |   # Frontend assets generated by Vite (not tracked by Git)
|   ├── dist/
|   |
|   |   # Static images like icons
|   ├── img/
|   |
|   |   # Kirby's media folder for thumbnails and more (not tracked by Git)
|   └── media/
|
|   # Kirby's core folder containing templates, blueprints, etc.
├── site/
|   ├── config/
|   |   |
|   |   |   # General configuration settings for Kirby and plugins
|   |   ├── config.php
|   |   |
|   |   |   # Builds a JSON-encoded `site` object for the frontend
|   |   |   # Used by Vue Router to populate routes, but can be extended by commonly used data
|   |   └── app-site.php
|   |
|   |   # Only relevant in multi-language setups
|   ├── languages/
|   |
|   ├── plugins/kirby-vue-kit/
|   |   |
|   |   |   # Core of the Vite integration plugin, mainly registers routes
|   |   ├── index.php
|   |   |
|   |   |   # Routes to handle `.json` requests and serving the `index.php` snippet
|   |   └── routes.php
|   |
|   |   # Templates for JSON content representations fetched by frontend
|   |   # Contains also index page (`_app-index.php`)
|   └── templates/
|       |
|       |   # Handles build asset paths, inlines the `site` object, includes SEO meta tags, etc.
|       └── _app-index.php
|
|   # Includes all frontend-related sources
├── src/
|   |
|   |   # `Header`, `Footer`, `Intro` and other components (auto imported on-demand)
|   ├── components/
|   |
|   |   # Composables for common actions
|   ├── composables/
|   |   |
|   |   |   # Announces any useful information for screen readers
|   |   ├── useAnnouncer.js
|   |   |
|   |   |   # Provides information about the current language
|   |   ├── useLanguages.js
|   |   |
|   |   |   # Retrieves pages from the content API
|   |   ├── useKirbyApi.js
|   |   |
|   |   |   # Returns page data for the current path, similarly to Kirby's `$page` object
|   |   ├── usePage.js
|   |   |
|   |   |   # Returns a object corresponding to Kirby's global `$site`
|   |   └── useSite.js
|   |
|   |   # Modules system entries will be auto installed
|   ├── modules/
|   |   |
|   |   |   # Installs the `v-kirbytext` directive to handle internal page links inside KirbyText
|   |   ├── kirbytext.js
|   |   |
|   |   |   # Initializes the Vue Router
|   |   └── router.js
|   |
|   |   # Vue.js views corresponding to Kirby templates
|   |   # Routes are being automatically resolved
|   ├── views/
|   |
|   ├── App.vue
|   ├── index.css
|   └── index.js
|
|   # Contains everything content and user data related (not tracked by Git)
├── storage/
|   ├── accounts/
|   ├── cache/
|   ├── content/
|   ├── logs/
|   └── sessions/
|
|   # Kirby CMS and other PHP dependencies (handled by Composer)
├── vendor/
|
|   # Environment variables for both Kirby and Vite (to be duplicated as `.env`)
├── .env.example
|
|   # Configuration file for Vite
└── vite.config.js

Caching

The frontend will store pages between individual routes/views. When the tab get reloaded, the data for each page is freshly fetched from the API once again.

Caching for Kirby and Vue 3 starterkit

Stale-While-Revalidate

The stale-while-revalidate mechanism for the usePage hook allows you to respond as quickly as possible with cached page data if available, falling back to the network request if it's not cached. The network request is then used to update the cached page data – which directly affects the view after lazily assigning changes (if any), thanks to Vue's reactivity.

Prerequisites

  • Node.js with npm (only required to build the frontend)
  • PHP 8.0+

Kirby is not a free software. You can try it for free on your local machine but in order to run Kirby on a public server you must purchase a valid license.

Setup

Composer

Kirby-related dependencies are managed via Composer and located in the vendor directory. Install them with:

composer install

Node Dependencies

Install npm dependencies:

npm ci

Environment Variables

Duplicate the .env.development.example as .env::

cp .env.development.example .env

Optionally, adapt it's values.

Vite will load .env files according to the docs:

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Static assets

During development Kirby can't access static files located in the src folder. Therefore it's necessary to create a symbolic link inside of the public folder:

ln -s $PWD/src/assets ./public/assets

Usage

Build Mode

During development a .lock file will be generated inside the src directory to let the backend now it runs in development mode. This file is deleted when running the build command.

ℹ️ Alternatively, you can set a KIRBY_MODE env variable containing either development or production to set the app mode programmatically and overwrite the .lock file mechanism. This may ease setups with Docker.

Development

You can start the development process with:

# Runs `npm run kirby` parallel to `vite`
npm run dev

Afterwards visit the app in your browser: http://127.0.0.1:8080

For Valet users: Of course you can use a virtual host alternatively!

Vite is used in combination with backend integration and only serves frontend assets, not the whole app. Thus, http://localhost:3000 won't be accessible.

The backend is served by the PHP built-in web server on http://127.0.0.1:8080 by default, but you can adapt the location in your .env file.

Production

Build optimized frontend assets to public/dist:

npm run build

Vite will generate a hashed version of all assets, including images and fonts saved inside src/assets. It will further create a manifest.json file with hash records etc.

Deployment

ℹ️ See ploi-deploy.sh for exemplary deployment instructions.

ℹ️ Some hosting environments require to uncomment RewriteBase / in .htaccess to make site links work.

Configuration

All development and production related configurations for both backend and frontend code are located in your .env file:

  • KIRBY_DEV_HOSTNAME and KIRBY_DEV_PORT specify the address where you wish the Kirby backend to be served from. It is used by the frontend to fetch content data as JSON.
  • Keys starting with VITE_ are available in your code following the import.meta.env.VITE_CUSTOM_VARIABLE syntax.

For example, setting KIRBY_CACHE to true is useful in production environment.

Content API Slug

To change the API slug to fetch JSON-encoded page data from, set

  • KIRBY_CONTENT_API_SLUG to a value of your liking (defaults to app). It can even be left empty to omit a slug altogether!

You can't use Kirby's internal API slug (defaults to api). If you insist on using api for your content endpoint, you can rename Kirby's by adding a KIRBY_API_SLUG key and set it to something other than api.

Multi-Language

Multiple languages are supported. A comprehensive introduction about multi-language setups may be found on the Kirby website.

To enable language handling, you don't have to edit the config.php manually. Just set

  • KIRBY_MULTILANG to true.
  • KIRBY_MULTILANG_DETECT to true (optional but recommended).

Then, visit the panel and add new languages by your liking. The Panel automatically renames all existing content and file meta data files and includes the language extension.

Language data is provided by the global site object, which can be accessed via the useSite() hook.

Stale-While-Revalidating

To keep page data fresh with stale-while-revalidate, set:

  • VITE_STALE_WHILE_REVALIDATE to true

Credits

License

MIT License © 2020-2023 Johann Schopplich

kirby-vue3-starterkit's People

Contributors

dependabot[bot] avatar dpschen avatar johannschopplich avatar kms-ploi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kirby-vue3-starterkit's Issues

router-view transition won't fade in on router.replace

Hey Johann,
at first i like to thank you a lot, for this great setup!
It works nicely, but i have one issue, with transitioning pages on route.replace.

App.vue

<router-view v-slot="{ Component, route }">
    <transition name="fade" mode="out-in">
        <component :is="Component" :key="route.path" />
    </transition>
</router-view>

That code fades pages out and in. Works like a charme.

But if the user or whoever navigates to a wrong url - the system redirects to the error page.
The fadeOut works, the path changes, useKirbyApi.js outputs the error.json - so far so good.
Unfortunately the router-view transition wont fade in again :(
Same behavior, if i manually replace the path somewhere else.

If i disable the mode="out-in" it works again, but without fading.
If the initial path is the error page (without redirect) it also fades in.
But not on router.replace!
If you have any idea how to force the fadeIn i would be really happy :)

Thx!

Deployment: What and how?

Developing a site with this Starter Kit was super nice, especially with the newer versions that even come with automatic component imports etc. Thank you!

Now it’s time for deployment, but I don’t understand how.

As far as I understood, Node is not required on the server, but only to build the frontend, right?

From the README:

Node.js with npm (only required to build the frontend)

  1. What folder do I need to deploy? The whole repository? Just public or just the contents of public? What does "point your server to public" mean?

I’ve tried a couple of things but I’m clueless how this should work.

Multi-language support

I'll be looking into multi-language support and was wondering if you already looked into it a bit yourself? If I find a good solution I'd be willing to contribute it to the core.

create pages from frontend

I want to create an api in which creates pages from the frontend to the example of Sonja Broda .

However the post-request from the vue-component (the form) is not working as it should. I'm figuring out what's happening, but could it be that Controllers don't work as expected in this Vue-Kirby boilerplate?

Vue.js devtools

I wonder if you need to setup something specific in order to have the vue.js devtools up and running. The plugin I am usually using, doesn't indicate that the page uses vue.js unfortunately and the vuejs tab doesn't show up in the web inspector. Any hints?

Enhancement: Sass?

Being trying to activate sass...put running into multiple errors? Had the same issues?

Queries not working

Route queries, used for the token for previewing drafts are not being passed correctly into the getPage function.
Query needs to be a rest parameter:

async function getPage(id, { revalidate = false, ...query } = {})

Language code duplication in URL causes error page redirection

Hi there! I ran into an issue with the router when setting up a multi-language site.

When pointing a link from a non-top-level url to a top-level url it redirects to the error page. This is because it appends the language code twice.

<router-link  
    :key="contact.uri"
    :to="`/${contact.uri}`"
>

or using a hardcoded path

<router-link  
    :key="contact.uri"
    :to="{path: '/contact'}"
>

or using "../"

<router-link  
    :key="contact.uri"
    :to="{path: '../contact'}"
>

So when you're on www.example.com/en/projects/house
and from there want to link to www.example.com/en/contact
it redirects to www.example.com/en/en/contact and thus goes to the error page.

Does it have something to do with the base url being built with the languageCode inside the router js file?

Thanks for any input!

Edit NOTE:
This only happens when deployed, it doesn't happen on localhost dev. (Maybe a Vite thing?)

Custom language variables best practice

Hi,

This is maybe more of a question than an issue. I would like to use custom language variables for certain buttons etc.
Unfortunately, translations specified in the e.g./languages/en.php file are not contained in the site.languages object.
In the kirby docs it says there is the t('...') helper function for multi-language setups to access these variables. Did you implement something similiar yet for this version of the starterkit? Or can you recommend an approach/a best practice to do so?

Thank you!

PHP / Kirby Routing

Hi Johann, thanks for the amazing plugin! Love your contributions to the Kirby community.

I'm just wondering if you're able to provide a small amount of guidance on using PHP routing with Vue managing the frontend of the website — how can we bypass the Vue Router and manage the route with PHP (eg, to make an API call from the server triggered by POST request, etc)?

I have a decent handle on Vue Router and Kirby's routing – but not together!

Undefined offset: 0 in snippets/vue-index.php

Fresh install PHP throws an error in vue-index:

snippets/vue-index.php

Removing the glob [0] makes it work in the pathToAsset function

return $root . basename(kirby()->roots()->index() . $root . $pattern);

Language switch best practise?

Hi there!

I have a multi-language setup and implementing a language switch.

In the standard PHP Starterkit I'd use the language code inside the url constructor to construct the corresponding second language url (same destination/path):

 <a href="<?= $page->url(kirby()->language()->code('en')) ?>">
    English
 </a>

(Hardcoded language code/name to explain)

In the Vue Starterkit router-link I'm thinking about setting the :to by combining a inactivelanguagecode (set in site-spa.php) and the current route.path.

        <router-link 
          :key="`${site.inactivelanguagecode + route.path}`"
          :to="`/${site.inactivelanguagecode + route.path}`"
          class="navigation__link"
        >
          <span>
            {{ site.inactivelanguagename }}
          </span>
        </router-link>

Is there a more proper and less hacky way?

Thanks!

EDIT: edited the router-link

Storing and accessing development/production variables in env

Hi @johannschopplich ! Thanks as always for an amazing framework.

Sorry if this is a n00b question, but I'm working with API Keys where I have one (unrestricted) key for dev and one restricted to the final domain for production. When the website runs a build I'd like it to use the production one and the unrestricted one during dev.

With Vite I can use import.meta.VITE_API_KEY in my front end component to get the value, however this always takes the value from the .env file, even after running a build and if I have a .env.production file with a different string as the same env value. Removing .env and using two.env.development / .env.production file crashes the dev process.

What am I missing here?

Thanks as always.

Multilanguage support

No issue, just an info maybe for the docs:
In order to make the multi-language work, you have to run npm run build first.
If you run npm run dev it won't resolve the multi language paths but throw a 404 error on the json file.

From the starterkit:
Unhandled Promise Rejection: Error: The requested URL /en/viteproxy/spa/photography.json failed with response error "Not Found".
or
Unhandled Promise Rejection: Error: The requested URL /en/viteproxy/spa/__site.json failed with response error "Not Found".

So on local, the multi-language works on 127.0.0.1 but not on localhost.

syntax error, unexpected 'static' (T_STATIC)

Hi there!

I tried to get this running, followed the install instructions and when I am told to visit the app at http://127.0.0.1:8080/, I get this error message:

syntax error, unexpected 'static' (T_STATIC)

20210604-001121_Screenshot_GoogleChrome

I have no idea, what any of this means and how I can fix this. 😓 Any ideas?

Thanks!

Draft preview not working

Hello! I'm having an issue getting previewing a page in "Drafts" to work. Whenever a page is in "Draft" mode and I try to open the page, using the token generated by the CMS, the page goes to the 404/error page.

I'm not quite sure what other information you might need - please let me know!

Alias

I'm having trouble using alias with your vite config file. Previously I would use:

'@': fileURLToPath(new URL('./src', import.meta.url))

and then <image src="@/assets/image.jpg />

However, this doesn't work with your setup (/src is not getting prepended to the path). Maybe it's because of the root option?

I've also tried "@": path.resolve(__dirname, "./src")

Basically I can not get images/files/fonts in the assets folder to resolve correctly. Any ideas/hints?
Thank you (and thanks for the great work on this).

<script> container exposing titles and listing status of all the top level pages as JSON

Hi there Johann! Thanks for the starterkit, works like a charm! Thanks again for the great work!

I have one question though: after building the site there's a <script> container left in the body tag exposing the titles, templates and listing statuses of all the top level pages as JSON, even the unpublished/hidden ones.

Is this on purpose? Because it leaves all the top level pages' info fully exposed to the public regardless if they're hidden pages or not. Like if I had a page I wanted to hide from the public, its URL etc. is still visible to the public and therefore still accessible (if set to "unlisted").

Or am I building it wrong?

Example:

<script id="site-data" type="application/json">
   {"children":[{"uri":"arbeiten","title":"Arbeiten","isListed":true,"template":"arbeiten","childTemplate":"arbeit"},
   {"uri":"publikationen","title":"Publikationen","isListed":true,"template":"publikationen","childTemplate":"publikation"},
   {"uri":"biografie","title":"Biografie","isListed":true,"template":"biografie","childTemplate":null},
   {"uri":"kontakt","title":"Kontakt","isListed":true,"template":"kontakt","childTemplate":null},
   {"uri":"error","title":"Error","isListed":false,"template":"error","childTemplate":null},
   {"uri":"home","title":"Home","isListed":false,"template":"home","childTemplate":null}],"languages":[],"title":"123"}
</script>

(?) Best Practice: Using Tags for filtered Collections

When i want to have a filter for my projects, i cannot really use the parameters from kirby, since they are not there in the vue frontend, right? https://getkirby.com/docs/cookbook/content/filtering-with-tags#tagcloud

Is there any best practice how to implement something like this?

I only can think of creating folders within pages and then "hard" linking my filter to these routes by lowercasing my tags? But that means the editor cannot create a new category by its own.

When building a vue component for this, i need to have fetch the get parameters and showing content accordingly, but that also doesn’t feel right.

Any ideas?

Build Issue: Page not found

Hey,

this is most likely a noob question so I hope you don't mind asking it here.

This is the first time I deploy a vue website and I am running into problems trying to build/deploy it. I followed the steps described in this repo. Consequently, the build process seems to run without errors, creating a manifest.json and an 'assets' folder with some js and css files. However, when I upload the /public directory on my server, I get an ' Page not found' error.

I am probably missing something obvious: isn't the whole page built so that the optimized files are in /public? What am I missing? Thanks in advance!

Outsource internal `kirby-vue-kit` into own repository

Hi Johann,

This is not an issue, but a request, would it possible to give the plugin kirby-vue-kit it's own repository and add it as a dependency of kirby-helpers, or include it as part of kirby-helpers itself? If you are ok with #2 I would be happy to refactor it as part of kirby-helpers and make a pull request.

Let me know,
Luke

Kirby caches path to assets?

With following .env settings:

KIRBY_CACHE=true
VITE_SERVICE_WORKER=true
VITE_STALE_WHILE_REVALIDATE=true

If I regenerate the assets with npm run build, the path in <?= vite()->js() ?> doesn't get updated to the latest hash specified in the manifest, because _app-index.php is cached.

Let me know if I'm misunderstanding something here! Would it be enough to just exclude the home page from ever being cached?

Meta-tags kirby-extended

I am currently configuring custom meta-tags for each note entry by using the starterkit. So far, I have added the metadata methods to my header.php like:

<?php $meta = $page->meta() ?>
// Canonical link (always) and robots (if configured)
<?= $meta->robots() ?>
...

While navigating between my blogposts I can see that the site title is being updated but not the other meta-tags (twitter-image, description etc..)

I have also extended my page model for template-specific meta data (models/note.php) to no avail (i.e. the image isn't updating when switching to other posts.

public function metadata(): array
    {
        $description = $this->summary()->or($this->text()->excerpt(140))->value();
        return [
            'description' => $description,
            'opengraph' => [
                'type' => 'article',
                'image' => $this->images()->first()->url(),
                // Open Graph object types can be defined in an array
                // with `namespace:` as prefix
                'namespace:article' => [
                    'author' => $this->author()->toUser()->name()->value(),
                    'published_time' => $this->date()->toDate('d F Y')
                ]
            ],
            'twitter' => [
              'image' => $this->images()->first()->url()
            ],
            'jsonld' => [
                'BlogPosting' => [
                    'headline' => $this->title()->value(),
                    'description' => $description
                ]
            ]
        ];
    }

Do I need to modify and rewrite all the meta-tags manually on the vue frontend inside hooks/usePage.js ?
I've noticed that the site title is being changed there:

if (!path) {
      // Set document title
      document.title = page.metaTitle;
...

Thanks in advance!

Custom Panel CSS file path

Hi! If I wanted to have a custom panel.css file, do you maybe know what path I'd have to use?

I tried a hardcoded http://127.0.0.1:3000/static/css/panel.css to a custom folder named "static" however unfortunately it's not loading into the <head> part of the panel though. The path is correct though. I don't actually know if it's an issue on my setup's side or a Vue Starterkit issue.

This is the config.php file's content:

    'panel' => [
        'install' => env('KIRBY_PANEL_INSTALL', false),
        'slug' => env('KIRBY_PANEL_SLUG', 'panel'),
        'css' => 'http://127.0.0.1:3000/static/css/panel.css'
    ],

Thanks! 😃

https://getkirby.com/docs/reference/system/options/panel#custom-panel-css

Router transitions

After a first quick test, router transitions only seem to work from child pages to parent pages.

When using transition mode="out-in", navigation breaks as the new page gets appended to the bottom of the current page.

What I tried in App.vue:

<transition :name="'fade'" mode="in-out">
    <router-view :key="route.path" />
</transition>
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

/service-worker.js 404

I'm trying to debug the service-worker offline but can't get the service-worker script to load with the vite dev server.

How to reproduce:

  • fresh install
  • (edit scripts/buildSw.js:3 require('fs/promises') to `require('fs').promises since the former breaks with node v12.18.3)
  • (run npm run build – don't know if it's necessary at this stage)
  • enable VITE_ENABLE_SW and VITE_ENABLE_SWR in .env
  • run npm run serve

Result

The service worker under http://localhost:3000/service-worker.js fails to load with a 404.

How are you debugging the service-worker locally?

Edge 44 not working

Hi, I noticed that the starterkit is not working in Edge 44 although it supports ESM. Always defaults to the Default.vue template without throwing any error message. Maybe that should be in the docs 🤷‍♂️

(Built a website but only noticed in the end that it doesn't work lol 😅)
vite legacy plugin did not help btw

.env files not loading

Here is another thing I found after some testing. The environment specific .env file is not being loaded. For example if you have a .env.development file and run vite in dev mode, it will actually just load the regular .env file.

Normally you would use loadEnv, and check the mode like this:

import { defineConfig, loadEnv } from 'vite' import vue from '@vitejs/plugin-vue' export default ({ mode }) => { process.env = {...process.env, ...loadEnv(mode, process.cwd())} return defineConfig ({...

In your case dotenv does not have access to the vite mode yet, so it always loads the "base" .env file.
The vite.config.js file can be adapted using the method above, however doing so means it's no longer possible to define the process environment variables as you have using the non VITE prefixed variables (process.env.VITE_MULTILANG = process.env.KIRBY_MULTILANG) etc.

I'm not sure what the solution is, but I will post back here when I have an idea.

Replacing default image block snippet

I am using Kirby blocks for my content and render it through my template page, let's say note.php like this:

$data = [
  'text' => ['html' => $page->text()->toBlocks()->toHtml()],
];

echo vite()->json($data);

I need to wrap some additional information to all my image tags and with a normal Kirby setup I could just create an image.php in snippets/blocks/ inside the template folder and it would replace the image block snippet. However i don't see my changes to the image block if I try to fetch the json data from note.php

curl http://localhost:8000/app/test/note-title.json

For reference only this is the image.php

<?php

/** @var \Kirby\Cms\Block $block */
$alt     = $block->alt();
$caption = $block->caption();
$crop    = $block->crop()->isTrue();
$link    = $block->link();
$ratio   = $block->ratio()->or('auto');
$src     = null;

if ($block->location() == 'web') {
    $src = $block->src()->esc();
} elseif ($image = $block->image()->toFile()) {
    $alt = $alt ?? $image->alt();
    $src = $image->url();
    $id = $image->id();
}

?>
<?php if ($src): ?>
<figure<?= attr(['data-ratio' => $ratio, 'data-crop' => $crop], ' ') ?>>
  <?php if ($link->isNotEmpty()): ?>
  <a href="<?= esc($link->toUrl()) ?>">
    <img src="<?= $src ?>" alt="<?= $alt->esc() ?>">
  </a>
  <?php else: ?>
  <img src="<?= $src ?>" data-id="<?= $id ?>" alt="<?= $alt->esc() ?>">
  <?php endif ?>

  <?php if ($caption->isNotEmpty()): ?>
  <figcaption>
    <?= $caption ?>
  </figcaption>
  <?php endif ?>
</figure>
<?php endif ?>

Access content from other pages

Hi there, pardon my question, but is it possible to use the Kirby "regular" chaining system like in the PHP starterkit after importing useSite?

For instance: in a component (not a view, I mean), is it possible to reference content from another page?

<button class="button" />
   {{ site.children.find('somepage').title }}
</button>

The "regular" chaining system would be like:
site()->children()->find('somepage')->title()

For now, it says
Unhandled Promise Rejection: TypeError: Array.prototype.find callback must be a function

Thx! 😃

Working with layouts and blocks

Hiya,
I'm trying to build my pages with layouts and blocks, but am having a real hard time with returning something I can work with on the frontend. This is a reduced code example:

about.php

<?php

$data = [
  'title' => $page->title()->value(),
  'metaTitle' => $page->customTitle()->or($page->title() . ' – ' . $site->title())->value(),
  'content' => $page->layout()->yaml(),
];

echo \Kirby\Data\Json::encode($data);

About.vue

<ul id="rendering">
      <li v-for="item in page.content">
        {{ item }}
      </li>
    </ul>

about.yaml

fields:
  layout:
    label: Page layout
    type: layout
    layouts:
      - "1/1"
      - "1/2, 1/2"
      - "1/3, 2/3"
      - "1/3, 1/3, 1/3"
    fieldsets:
      - heading
      - text
      - image

And this results in:

[
  "{\"attrs\":[]",
  "\"columns\":[{\"blocks\":[{\"content\":{\"1\\/3\":\"blocks\",\"content\":\"text\"},\"text\":\"<p>w two hals<\\/p>\",\"id\":false,\"4bf8fb48-4778-43e7-bf6a-8f3aff1d44a7\":\"isHidden\"}],\"content\":\"level\",\"h1\":\"text\"}]",
  "\"This is H!\":\"id\"}",
  "{\"ff98539c-e102-4137-a3fb-2cf1cb0b40cb\":[]",
  "\"isHidden\":[{\"type\":[{\"type\":{\"<p>And this is the following on text<\\/p>\":\"id\",\"5c4d8710-baaa-4ecf-90c9-c78de08f0260\":\"isHidden\"},\"text\":\"id\",\"56430216-c475-45d9-a667-9f729d55fc70\":false,\"width\":\"1\\/2\"}],\"heading\":\"id\",\"06c5cc06-8baf-416f-ac55-a69e3f5032b8\":\"width\"},{\"1\\/1\":[{\"id\":{\"type\":\"text\"},\"83b8e93a-6a5a-4201-91c1-a4ddf93ee722\":\"attrs\",\"columns\":false,\"blocks\":\"content\"}],\"id\":\"f3de5d32-7d3c-42c0-92d0-6f3401cd4c54\",\"attrs\":\"columns\"}]",
  "\"blocks\":\"content\"}",
  "{\"level\":[]",
  "\"h2\":[{\"text\":[{\"level\":{\"id\":\"abe0f890-aab0-4312-9957-acb9d2032b40\",\"width\":\"2\\/3\"},\"h2\":\"text\",\"This is a heading\":false,\"id\":\"b1816149-e675-4e49-b15c-e726b8092c1d\"}],\"w one half\":\"id\",\"3adc44e7-64a2-4696-b24d-80eb4250c643\":\"isHidden\"},{\"type\":[{\"isHidden\":{\"id\":\"e50c3002-07e6-49c0-b0d8-d77577674550\"},\"type\":\"heading\",\"id\":false,\"a87e13ca-8e21-4534-8b05-86b8e1fde184\":\"width\"}],\"heading\":\"id\",\"5309b4e9-f71b-481d-9640-7f36999c2e66\":\"width\"}]",
  "\"1\\/2\":\"blocks\"}"
]

Which makes me a sad panda 😢 Any pointers on how I should be approaching this? Thank you for any insights!

Deployed vite scripts refers to localhost

I just cloned the project.

And did the steps in the README.md (composer install && npm install && cp .env.example .env && ln -s $PWD/src/assets ./public/assets)

When running npm i && npm run build locally and then upload the whole repository (without node_modules) i can access the kirby backend on my server, but the fronted tries to access the following link.

  <script src="http://localhost:3000/@vite/client" type="module"></script> 

  <script src="http://localhost:3000/index.js" type="module"></script> 

Anything related to this line? site/plugins/kirby-vue/classes/KirbyVue/Vite.php#L136

Since i only have a normal shared hosting server and no node server, i cannot run npm i && npm run build on the server as suggested in the README.md

Domain is pointing to public/ and KIRBY_PANEL_INSTALL=true is set in the .env on the server.

What am i missing or doing wrong here?

Running npm run dev locally works fine.

Using Query Parameters or URL Parameters

At first i'd like to thank you for your great job with the vue3 starterkit.

now after i've started to work with your setup i'd like to include a seach, when i use the search from the cookbook it uses query parameters for the search. when i try something like this it doesn't work because of the changed routing the parameters are not available in the controller.

can you tell me how to solve the problem using query parameters with your setup.

Sitemap.xml

Hello,

i saw you removed the sitemapper plugin. Are there any other ways to generate a sitemap.xml? Or how can i route the application to the sitemap.xml correctly?

Page nesting

Successfully finished a site a couple days ago with your starterkit – thx, worked great!

Concerning another project: is the following nesting structure supported by your starterkit:

Page 1
Page 2
Page 3
   |
   Page 3.1
   Page 3.2
      |
      Page 3.2.1
      Page 3.2.2
      Page 3.2.3

Urls would then be for example
www.example.com/cities/rome/theatres
www.example.com/cities/rome/museums
www.example.com/cities/rome/restaurants

Or is the nesting limited to for example
www.example.com/cities/rome

Thanks again!

(Sorry, don't know how to add the github "question" label.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.